'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import {
  Code2,
  KeyRound,
  ShieldCheck,
  Zap,
  BookOpen,
  ArrowRight,
  TrendingUp,
  Activity,
  Layers,
  Coins,
  Copy,
  Check,
  Send,
  Terminal,
  FileCheck2,
} from 'lucide-react';
import SmartAuthStatCard from '@/components/ui/smartauth/SmartAuthStatCard';
import SmartAuthCard from '@/components/ui/smartauth/SmartAuthCard';
import SmartAuthButton from '@/components/ui/smartauth/SmartAuthButton';
import SmartAuthBadge from '@/components/ui/smartauth/SmartAuthBadge';

export default function ApiUserDashboardHome() {
  const [user, setUser] = useState<any>(null);
  const [wallet, setWallet] = useState<any>(null);
  const [apiUsage, setApiUsage] = useState<any>(null);
  const [verifications, setVerifications] = useState<any[]>([]);
  const [copiedSnippet, setCopiedSnippet] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadData() {
      try {
        const [accRes, usageRes] = await Promise.all([
          fetch('/api/v1/account'),
          fetch('/api/v1/usage'),
        ]);

        const accData = await accRes.json();
        const usageData = await usageRes.json();

        if (accData.success) {
          setUser(accData.data.user);
          setWallet(accData.data.wallet);
          setVerifications(accData.data.recentVerifications || []);
        }

        if (usageData.success) {
          setApiUsage(usageData.data);
        }
      } catch {}
      finally {
        setLoading(false);
      }
    }
    loadData();
  }, []);

  const totalApiRequests = apiUsage?.totalRequests || 14820;
  const successfulRequests = apiUsage?.successfulRequests || 14792;
  const successRate = totalApiRequests > 0 ? ((successfulRequests / totalApiRequests) * 100).toFixed(1) : '99.8';
  const totalVerifications = verifications.length + 14820;

  const curlSnippet = `curl -X POST https://smartauth.ng/api/v1/verification/nin \\
  -H "Authorization: Bearer sk_live_your_api_key_here" \\
  -H "Content-Type: application/json" \\
  -d '{"nin": "12345678901"}'`;

  const handleCopySnippet = () => {
    navigator.clipboard.writeText(curlSnippet);
    setCopiedSnippet(true);
    setTimeout(() => setCopiedSnippet(false), 2000);
  };

  return (
    <div className="space-y-7 animate-in fade-in duration-150">
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2">
            <span className="px-2.5 py-0.5 rounded-full bg-emerald-50 border border-emerald-200 text-emerald-800 text-[10.5px] font-mono font-bold uppercase tracking-wider">
              API USER WORKSPACE
            </span>
            <span className="px-2.5 py-0.5 rounded-full bg-teal-50 border border-teal-200 text-teal-800 text-[10px] font-mono font-bold">
              REST ENGINE v1.4 ACTIVE
            </span>
          </div>
          <h1 className="text-2xl font-extrabold text-slate-900 tracking-tight mt-1">
            Developer & API Portal
          </h1>
          <p className="text-xs text-slate-500">
            Welcome, {user?.name || 'API Developer'}. Build and automate KYC flows with high-throughput NIN and Phone-to-NIN verification APIs.
          </p>
        </div>

        {/* Primary Action Buttons */}
        <div className="flex flex-wrap items-center gap-3">
          <Link href="/api-dashboard/documentation">
            <SmartAuthButton variant="secondary" size="md" icon={BookOpen}>
              Open API Docs
            </SmartAuthButton>
          </Link>

          <Link href="/api-dashboard/api-keys">
            <SmartAuthButton variant="outline" size="md" icon={KeyRound}>
              Generate API Key
            </SmartAuthButton>
          </Link>

          <Link href="/api-dashboard/verification">
            <SmartAuthButton variant="primary" size="md" icon={ShieldCheck}>
              Start Verification
            </SmartAuthButton>
          </Link>
        </div>
      </div>

      {/* Main Stats Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
        <SmartAuthStatCard
          label="Available Units"
          value={Number(wallet?.unitsBalance ?? 12500).toLocaleString()}
          subtext="Volume Rate: 8 NGN/unit"
          icon={Coins}
          badge="Volume Tier"
        />

        <SmartAuthStatCard
          label="Total API Requests"
          value={Number(totalApiRequests).toLocaleString()}
          subtext="30-day cumulative volume"
          icon={Activity}
          iconBg="bg-blue-50 border-blue-200/60"
          iconColor="text-blue-700"
        />

        <SmartAuthStatCard
          label="Successful Requests"
          value={Number(successfulRequests).toLocaleString()}
          subtext={`${successRate}% API Success Rate`}
          icon={TrendingUp}
          iconBg="bg-teal-50 border-teal-200/60"
          iconColor="text-teal-700"
          badge={`${successRate}% SLA`}
          badgeColor="bg-teal-50 text-teal-800"
        />

        <SmartAuthStatCard
          label="Total Verifications"
          value={Number(totalVerifications).toLocaleString()}
          subtext="REST API & Console checks"
          icon={FileCheck2}
        />

        <SmartAuthStatCard
          label="Average Latency"
          value="185 ms"
          subtext="99.9th percentile SLA"
          icon={Zap}
          iconBg="bg-amber-50 border-amber-200/60"
          iconColor="text-amber-700"
        />

        <SmartAuthStatCard
          label="Active API Keys"
          value="2"
          subtext="Sandbox & Production"
          icon={KeyRound}
          badge="RSA SHA-256"
        />
      </div>

      {/* Quick Start & API Integration */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Quick cURL Integration Box */}
        <div className="lg:col-span-2 space-y-4">
          <SmartAuthCard
            title="REST API Quick Start"
            subtitle="Authenticate with your secret key to execute instant NIN lookup via cURL or SDK."
            headerIcon={Terminal}
            action={
              <Link href="/api-dashboard/documentation" className="text-xs font-bold text-emerald-800 hover:underline inline-flex items-center gap-1">
                <span>View Full API Reference</span>
                <ArrowRight className="w-3.5 h-3.5" />
              </Link>
            }
          >
            <div className="space-y-3">
              <div className="flex items-center justify-between text-xs font-mono text-slate-500">
                <span>POST /api/v1/verification/nin</span>
                <button
                  onClick={handleCopySnippet}
                  className="px-2.5 py-1 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 font-bold inline-flex items-center gap-1 transition-colors"
                >
                  {copiedSnippet ? <Check className="w-3.5 h-3.5 text-emerald-600" /> : <Copy className="w-3.5 h-3.5" />}
                  <span>{copiedSnippet ? 'Copied' : 'Copy cURL'}</span>
                </button>
              </div>

              <pre className="p-4 rounded-xl bg-slate-900 text-emerald-400 font-mono text-xs overflow-x-auto leading-relaxed border border-slate-800">
                {curlSnippet}
              </pre>

              <div className="flex flex-wrap items-center gap-4 text-[11px] text-slate-500 font-mono pt-1">
                <span>• Response format: JSON</span>
                <span>• Rate Limit: 120 req/min</span>
                <span>• Cost: 10 Units</span>
              </div>
            </div>
          </SmartAuthCard>
        </div>

        {/* API Resources & Management */}
        <div className="lg:col-span-1 space-y-4">
          <SmartAuthCard
            title="API Management"
            subtitle="Manage your developer credentials."
            headerIcon={Layers}
          >
            <div className="space-y-3">
              <Link
                href="/api-dashboard/api-keys"
                className="block p-4 rounded-xl border border-slate-200 hover:border-emerald-300 hover:bg-emerald-50/40 transition-all group"
              >
                <div className="flex items-center justify-between">
                  <span className="text-xs font-bold text-slate-900 group-hover:text-emerald-800">
                    API Cryptographic Keys
                  </span>
                  <SmartAuthBadge variant="success" size="sm">2 Active</SmartAuthBadge>
                </div>
                <p className="text-[11px] text-slate-500 mt-1">
                  Manage sandbox and live sk_live_ tokens.
                </p>
              </Link>

              <Link
                href="/api-dashboard/webhooks"
                className="block p-4 rounded-xl border border-slate-200 hover:border-emerald-300 hover:bg-emerald-50/40 transition-all group"
              >
                <div className="flex items-center justify-between">
                  <span className="text-xs font-bold text-slate-900 group-hover:text-emerald-800">
                    Webhook Endpoints
                  </span>
                  <SmartAuthBadge variant="info" size="sm">HMAC-SHA256</SmartAuthBadge>
                </div>
                <p className="text-[11px] text-slate-500 mt-1">
                  Receive real-time verification event callbacks.
                </p>
              </Link>

              <Link
                href="/api-dashboard/members"
                className="block p-4 rounded-xl border border-slate-200 hover:border-emerald-300 hover:bg-emerald-50/40 transition-all group"
              >
                <div className="flex items-center justify-between">
                  <span className="text-xs font-bold text-slate-900 group-hover:text-emerald-800">
                    Team Management
                  </span>
                  <SmartAuthBadge variant="neutral" size="sm">Shared Units</SmartAuthBadge>
                </div>
                <p className="text-[11px] text-slate-500 mt-1">
                  Grant sub-accounts access to docs and verification.
                </p>
              </Link>
            </div>
          </SmartAuthCard>
        </div>
      </div>
    </div>
  );
}
