'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import {
  FileCheck2,
  ShieldCheck,
  Zap,
  ArrowRight,
  TrendingUp,
  Clock,
  Sparkles,
  Coins,
  Send,
  CheckCircle2,
  AlertCircle,
} 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 StandardUserDashboard() {
  const [user, setUser] = useState<any>(null);
  const [wallet, setWallet] = useState<any>(null);
  const [verifications, setVerifications] = useState<any[]>([]);
  const [apiAccessStatus, setApiAccessStatus] = useState<string>('NOT_APPLIED');
  const [loading, setLoading] = useState(true);

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

        const accData = await accRes.json();
        if (accData.success) {
          setUser(accData.data.user);
          setWallet(accData.data.wallet);
          setVerifications(accData.data.recentVerifications || []);
        }

        const reqData = await reqRes.json();
        if (reqData.success && reqData.data?.request) {
          setApiAccessStatus(reqData.data.request.status);
        }
      } catch {}
      finally {
        setLoading(false);
      }
    }
    loadData();
  }, []);

  const totalVerifications = verifications.length;
  const successfulVerifications = verifications.filter((v) => v.status === 'SUCCESS').length;
  const successRate = totalVerifications > 0 ? ((successfulVerifications / totalVerifications) * 100).toFixed(0) : '100';

  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>
          <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">
            STANDARD USER PORTAL
          </span>
          <h1 className="text-2xl font-extrabold text-slate-900 tracking-tight mt-1">
            Identity Verification Desk
          </h1>
          <p className="text-xs text-slate-500">
            Welcome back, {user?.name || 'User'}. Perform National Identification Number (NIN) authentication, phone linkage checks, and review identity records in real-time.
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          <Link href="/dashboard/verification">
            <SmartAuthButton variant="primary" size="md" icon={ShieldCheck}>
              Start Verification
            </SmartAuthButton>
          </Link>

          <Link href="/dashboard/api-access">
            <SmartAuthButton variant="outline" size="md" icon={Zap}>
              Request API Access
            </SmartAuthButton>
          </Link>
        </div>
      </div>

      {/* Main Dashboard Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
        <SmartAuthStatCard
          label="Available Units"
          value={`${Number(wallet?.unitsBalance ?? 1000).toLocaleString()}`}
          subtext="Standard Verification Rate: 10 units/check"
          icon={Coins}
          badge="Instant Funding"
          badgeColor="bg-emerald-50 text-emerald-800"
        />

        <SmartAuthStatCard
          label="Total Verifications"
          value={totalVerifications.toString()}
          subtext="National Identity & Phone matches"
          icon={FileCheck2}
          iconBg="bg-blue-50 border-blue-200/60"
          iconColor="text-blue-700"
        />

        <SmartAuthStatCard
          label="Successful Verifications"
          value={successfulVerifications.toString()}
          subtext={`${successRate}% Match Success Rate`}
          icon={CheckCircle2}
          iconBg="bg-teal-50 border-teal-200/60"
          iconColor="text-teal-700"
          badge={`${successRate}% Success`}
          badgeColor="bg-teal-50 text-teal-800"
        />

        <SmartAuthStatCard
          label="API Access Status"
          value={apiAccessStatus === 'PENDING' ? 'Under Review' : apiAccessStatus === 'APPROVED' ? 'Approved' : 'Standard'}
          subtext={apiAccessStatus === 'PENDING' ? 'Compliance team reviewing request' : 'Apply for high-volume REST API access'}
          icon={Zap}
          iconBg="bg-amber-50 border-amber-200/60"
          iconColor="text-amber-700"
          badge={apiAccessStatus === 'PENDING' ? 'PENDING' : 'UPGRADE'}
          badgeColor={apiAccessStatus === 'PENDING' ? 'bg-amber-100 text-amber-900' : 'bg-emerald-100 text-emerald-900'}
        />
      </div>

      {/* Two Column Layout: Verification Services & Recent Activity */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Verification Services Box */}
        <div className="lg:col-span-1 space-y-4">
          <SmartAuthCard
            title="Available Services"
            subtitle="Choose an identity verification engine to begin."
            headerIcon={ShieldCheck}
          >
            <div className="space-y-3">
              <Link
                href="/dashboard/verification"
                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">
                    NIN Identity Lookup
                  </span>
                  <SmartAuthBadge variant="success" size="sm">10 Units</SmartAuthBadge>
                </div>
                <p className="text-[11px] text-slate-500 mt-1">
                  11-digit National Identification Number validation against NIMC registry.
                </p>
              </Link>

              <Link
                href="/dashboard/verification"
                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">
                    Phone-to-NIN Match
                  </span>
                  <SmartAuthBadge variant="warning" size="sm">15 Units</SmartAuthBadge>
                </div>
                <p className="text-[11px] text-slate-500 mt-1">
                  Cross-verify registered SIM phone number with NIN record.
                </p>
              </Link>

              <Link
                href="/dashboard/verification"
                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">
                    BVN Verification Check
                  </span>
                  <SmartAuthBadge variant="info" size="sm">20 Units</SmartAuthBadge>
                </div>
                <p className="text-[11px] text-slate-500 mt-1">
                  Bank Verification Number identity and date-of-birth match.
                </p>
              </Link>
            </div>
          </SmartAuthCard>
        </div>

        {/* Recent Verification Activity Table */}
        <div className="lg:col-span-2">
          <SmartAuthCard
            title="Recent Activity"
            subtitle="Latest identity requests submitted through your workspace."
            headerIcon={Clock}
            action={
              <Link href="/dashboard/activity" className="text-xs font-bold text-emerald-800 hover:underline inline-flex items-center gap-1">
                <span>View Full Log</span>
                <ArrowRight className="w-3.5 h-3.5" />
              </Link>
            }
          >
            {verifications.length > 0 ? (
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead>
                    <tr className="border-b border-slate-100 text-slate-500 font-mono">
                      <th className="pb-3 font-semibold">Request ID</th>
                      <th className="pb-3 font-semibold">Type</th>
                      <th className="pb-3 font-semibold">Status</th>
                      <th className="pb-3 font-semibold">Units Charged</th>
                      <th className="pb-3 font-semibold">Timestamp</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {verifications.map((v) => (
                      <tr key={v.id} className="hover:bg-slate-50 transition-colors">
                        <td className="py-3 font-mono font-bold text-slate-900">{v.requestId}</td>
                        <td className="py-3">
                          <span className="font-semibold text-slate-700">{v.verificationType}</span>
                        </td>
                        <td className="py-3">
                          <SmartAuthBadge variant={v.status === 'SUCCESS' ? 'success' : 'error'} size="sm">
                            {v.status}
                          </SmartAuthBadge>
                        </td>
                        <td className="py-3 font-mono text-slate-600">-{v.unitsCharged} Units</td>
                        <td className="py-3 font-mono text-slate-400">
                          {new Date(v.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="text-center py-10 space-y-2">
                <div className="w-10 h-10 rounded-full bg-slate-100 flex items-center justify-center mx-auto text-slate-400">
                  <Clock className="w-5 h-5" />
                </div>
                <p className="text-xs font-mono text-slate-500">No verification activity recorded yet.</p>
                <Link href="/dashboard/verification">
                  <SmartAuthButton size="sm" variant="primary" icon={ShieldCheck}>
                    Start First Verification
                  </SmartAuthButton>
                </Link>
              </div>
            )}
          </SmartAuthCard>
        </div>
      </div>
    </div>
  );
}
