'use client';

import React, { useState, useEffect } from 'react';
import { Clock, Search, Download, ShieldCheck, CheckCircle2, AlertCircle } from 'lucide-react';
import SmartAuthCard from '@/components/ui/smartauth/SmartAuthCard';
import SmartAuthButton from '@/components/ui/smartauth/SmartAuthButton';
import SmartAuthBadge from '@/components/ui/smartauth/SmartAuthBadge';

export default function StandardUserActivityPage() {
  const [logs, setLogs] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState('ALL');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchLogs() {
      try {
        const res = await fetch('/api/v1/logs');
        const data = await res.json();
        if (data.success) {
          setLogs(data.data.logs || []);
        }
      } catch {}
      finally {
        setLoading(false);
      }
    }
    fetchLogs();
  }, []);

  const filteredLogs = logs.filter((log) => {
    const matchesSearch =
      log.requestId?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      log.verificationType?.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesType = filterType === 'ALL' || log.verificationType === filterType;
    return matchesSearch && matchesType;
  });

  const exportCSV = () => {
    const headers = ['Request ID', 'Type', 'Status', 'Units Charged', 'Latency (ms)', 'Timestamp'];
    const rows = filteredLogs.map((l) => [
      l.requestId,
      l.verificationType,
      l.status,
      l.unitsCharged,
      l.latencyMs,
      new Date(l.createdAt).toISOString(),
    ]);

    const csvContent = 'data:text/csv;charset=utf-8,' + [headers.join(','), ...rows.map((e) => e.join(','))].join('\n');
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement('a');
    link.setAttribute('href', encodedUri);
    link.setAttribute('download', `smartauth_verification_activity_${Date.now()}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  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>
          <h1 className="text-2xl font-extrabold text-slate-900 tracking-tight">Activity Logs</h1>
          <p className="text-xs text-slate-500 mt-1">Audit log of all identity verifications executed in your account.</p>
        </div>
        <SmartAuthButton variant="outline" size="md" icon={Download} onClick={exportCSV}>
          Export CSV
        </SmartAuthButton>
      </div>

      {/* Table Card */}
      <SmartAuthCard
        title="Verification Requests History"
        subtitle={`Showing ${filteredLogs.length} verified operations.`}
        headerIcon={Clock}
      >
        {/* Filters */}
        <div className="flex flex-wrap items-center justify-between gap-3 mb-4">
          <div className="relative w-full sm:w-72">
            <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
            <input
              type="text"
              placeholder="Search Request ID..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-9 pr-4 py-2 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
            />
          </div>

          <div className="flex items-center gap-2">
            {['ALL', 'NIN', 'PHONE_NIN', 'BVN'].map((type) => (
              <button
                key={type}
                onClick={() => setFilterType(type)}
                className={`px-3 py-1.5 rounded-lg text-xs font-mono font-bold transition-colors ${
                  filterType === type
                    ? 'bg-emerald-700 text-white shadow-2xs'
                    : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                }`}
              >
                {type}
              </button>
            ))}
          </div>
        </div>

        {filteredLogs.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">Verification Type</th>
                  <th className="pb-3 font-semibold">Status</th>
                  <th className="pb-3 font-semibold">Units Debited</th>
                  <th className="pb-3 font-semibold">Latency</th>
                  <th className="pb-3 font-semibold">Date & Time</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filteredLogs.map((l) => (
                  <tr key={l.id} className="hover:bg-slate-50 transition-colors">
                    <td className="py-3 font-mono font-bold text-slate-900">{l.requestId}</td>
                    <td className="py-3 font-semibold text-slate-700">{l.verificationType}</td>
                    <td className="py-3">
                      <SmartAuthBadge variant={l.status === 'SUCCESS' ? 'success' : 'error'} size="sm">
                        {l.status}
                      </SmartAuthBadge>
                    </td>
                    <td className="py-3 font-mono text-slate-600">-{l.unitsCharged} Units</td>
                    <td className="py-3 font-mono text-slate-400">{l.latencyMs} ms</td>
                    <td className="py-3 font-mono text-slate-500">
                      {new Date(l.createdAt).toLocaleString()}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="text-xs text-slate-400 font-mono text-center py-8">No matching verification logs found.</p>
        )}
      </SmartAuthCard>
    </div>
  );
}
