'use client';

import React, { useState, useEffect } from 'react';
import NINAuthSidebar from '@/components/dashboard/NINAuthSidebar';
import NINAuthHeader from '@/components/dashboard/NINAuthHeader';
import {
  Search,
  SlidersHorizontal,
  Download,
  Eye,
  X,
  FileText,
  ShieldCheck,
  RefreshCw,
  FolderOpen,
} from 'lucide-react';

export default function VerificationLogsPage() {
  const [user, setUser] = useState<any>(null);
  const [logs, setLogs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('ALL');
  const [selectedLog, setSelectedLog] = useState<any>(null);

  const fetchLogs = async () => {
    setLoading(true);
    try {
      const [accRes, logsRes] = await Promise.all([
        fetch('/api/v1/account'),
        fetch('/api/v1/logs'),
      ]);
      const accData = await accRes.json();
      if (accData.success) {
        setUser(accData.data.user);
      }
      const logsData = await logsRes.json();
      if (logsData.success) {
        setLogs(logsData.data || []);
      }
    } catch {}
    finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLogs();
  }, []);

  const filteredLogs = logs.filter((l) => {
    const q = searchTerm.toLowerCase();
    const matchSearch =
      l.requestId.toLowerCase().includes(q) ||
      l.status.toLowerCase().includes(q) ||
      l.verificationType.toLowerCase().includes(q);
    const matchStatus = statusFilter === 'ALL' || l.status.toUpperCase() === statusFilter;
    return matchSearch && matchStatus;
  });

  const handleDownloadReport = () => {
    const csvContent =
      'data:text/csv;charset=utf-8,' +
      ['Request ID,Timestamp,Type,Status,Units Charged,Mode']
        .concat(
          filteredLogs.map(
            (l) =>
              `"${l.requestId}","${new Date(l.createdAt).toISOString()}","${l.verificationType}","${l.status}","${l.unitsCharged}","${l.mode}"`
          )
        )
        .join('\n');
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement('a');
    link.setAttribute('href', encodedUri);
    link.setAttribute('download', `smartauth_verification_logs_${Date.now()}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="flex min-h-screen bg-[#f8fafc] text-slate-900 font-sans selection:bg-emerald-500/20">
      <NINAuthSidebar
        collapsed={sidebarCollapsed}
        onToggleCollapse={() => setSidebarCollapsed(!sidebarCollapsed)}
        userRole={user?.role}
      />

      <div className="flex-1 flex flex-col min-w-0">
        <NINAuthHeader
          user={user}
          onToggleSidebar={() => setSidebarCollapsed(!sidebarCollapsed)}
        />

        <main className="flex-1 p-6 sm:p-8 space-y-6 overflow-y-auto max-w-7xl">
          {/* Header */}
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div>
              <h1 className="text-2xl font-extrabold text-slate-900 tracking-tight">
                Verification Logs
              </h1>
              <p className="text-xs text-slate-500 mt-1">
                Real-time audit log of all identity verification transactions processed in MySQL.
              </p>
            </div>

            <button
              onClick={fetchLogs}
              disabled={loading}
              className="px-3.5 py-2 rounded-xl bg-white border border-slate-200 text-slate-600 hover:bg-slate-50 text-xs font-semibold shadow-sm flex items-center gap-1.5 transition-colors"
            >
              <RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin text-emerald-600' : ''}`} />
              <span>Refresh Logs</span>
            </button>
          </div>

          {/* Main Card */}
          <div className="bg-white rounded-2xl border border-slate-200/90 shadow-sm p-6 sm:p-7 space-y-6">
            {/* Toolbar */}
            <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-100 pb-4">
              <div className="text-xs font-mono font-bold text-slate-500 uppercase tracking-wider">
                ALL VERIFICATION LOGS ({filteredLogs.length})
              </div>

              <div className="flex flex-wrap items-center gap-3">
                {/* Search Box */}
                <div className="relative min-w-[200px] sm:min-w-[240px]">
                  <Search className="w-4 h-4 text-slate-400 absolute left-3 top-2.5" />
                  <input
                    type="text"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    placeholder="Search request ID, type..."
                    className="w-full bg-slate-50 border border-slate-200 rounded-xl pl-9 pr-3.5 py-2 text-xs text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-emerald-500"
                  />
                </div>

                {/* Status Filter */}
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="px-3 py-2 rounded-xl border border-slate-200 bg-white text-xs font-semibold text-slate-700 focus:outline-none focus:border-emerald-500 shadow-sm"
                >
                  <option value="ALL">All Status</option>
                  <option value="SUCCESS">Success</option>
                  <option value="VERIFIED">Verified</option>
                  <option value="FAILED">Failed</option>
                </select>

                {/* Download Report Button */}
                <button
                  type="button"
                  onClick={handleDownloadReport}
                  className="flex items-center gap-2 px-4 py-2 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 text-xs font-semibold text-slate-800 transition-colors shadow-sm"
                >
                  <span>Export CSV</span>
                  <Download className="w-3.5 h-3.5 text-slate-500" />
                </button>
              </div>
            </div>

            {/* Table */}
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs font-mono">
                <thead>
                  <tr className="border-b border-slate-200 text-slate-500 text-[11px]">
                    <th className="py-3 px-3">REQUEST ID</th>
                    <th className="py-3 px-3">TIMESTAMP</th>
                    <th className="py-3 px-3">MEDIUM</th>
                    <th className="py-3 px-3">STATUS</th>
                    <th className="py-3 px-3">UNITS</th>
                    <th className="py-3 px-3 text-right">ACTION</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100 text-slate-700">
                  {filteredLogs.length > 0 ? (
                    filteredLogs.map((log) => (
                      <tr key={log.id} className="hover:bg-slate-50 transition-colors">
                        <td className="py-3.5 px-3 font-bold text-emerald-700">
                          {log.requestId}
                        </td>
                        <td className="py-3.5 px-3 text-slate-500">
                          {new Date(log.createdAt).toLocaleString()}
                        </td>
                        <td className="py-3.5 px-3 font-semibold text-slate-800">
                          {log.verificationType || 'NIN'}
                        </td>
                        <td className="py-3.5 px-3">
                          <span
                            className={`px-2.5 py-0.5 rounded-full text-[10px] font-bold ${
                              log.status === 'SUCCESS' || log.status === 'VERIFIED'
                                ? 'bg-emerald-50 text-emerald-800 border border-emerald-200'
                                : 'bg-rose-50 text-rose-800 border border-rose-200'
                            }`}
                          >
                            {log.status}
                          </span>
                        </td>
                        <td className="py-3.5 px-3 text-slate-600 font-semibold">
                          {log.unitsCharged ? `${log.unitsCharged} Units` : '0 Units'}
                        </td>
                        <td className="py-3.5 px-3 text-right">
                          <button
                            onClick={() => setSelectedLog(log)}
                            className="px-3 py-1 bg-slate-100 hover:bg-slate-200 text-slate-700 text-xs font-semibold rounded-lg transition-colors inline-flex items-center gap-1 font-sans"
                          >
                            <Eye className="w-3.5 h-3.5" />
                            Inspect
                          </button>
                        </td>
                      </tr>
                    ))
                  ) : null}
                </tbody>
              </table>

              {/* Empty State */}
              {filteredLogs.length === 0 && !loading && (
                <div className="py-16 flex flex-col items-center justify-center space-y-3 text-center">
                  <div className="w-14 h-14 rounded-2xl bg-slate-100 flex items-center justify-center text-slate-400">
                    <FolderOpen className="w-7 h-7" />
                  </div>
                  <h3 className="text-sm font-bold text-slate-800">
                    No verification logs recorded yet
                  </h3>
                  <p className="text-xs text-slate-500 max-w-sm">
                    Perform a verification query on the Verification Desk or execute an API call to generate live logs.
                  </p>
                </div>
              )}
            </div>
          </div>

          {/* Inspect Modal */}
          {selectedLog && (
            <div className="fixed inset-0 bg-black/40 backdrop-blur-sm z-50 flex items-center justify-center p-4">
              <div className="bg-white w-full max-w-xl rounded-2xl p-6 border border-slate-200 space-y-4 shadow-2xl animate-in fade-in zoom-in-95 duration-150">
                <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                  <div className="space-y-0.5">
                    <h3 className="text-base font-bold text-slate-900">
                      Request ID: {selectedLog.requestId}
                    </h3>
                    <p className="text-xs text-slate-500 font-mono">
                      Timestamp: {new Date(selectedLog.createdAt).toLocaleString()} • Units: {selectedLog.unitsCharged}
                    </p>
                  </div>
                  <button onClick={() => setSelectedLog(null)} className="text-slate-400 hover:text-slate-700 p-1">
                    <X className="w-5 h-5" />
                  </button>
                </div>

                <div className="space-y-2">
                  <span className="text-xs font-bold text-slate-700 flex items-center gap-1.5">
                    <ShieldCheck className="w-4 h-4 text-emerald-600" />
                    Masked Response Payload (NDPR Compliant)
                  </span>
                  <pre className="p-4 rounded-xl bg-slate-900 text-emerald-400 text-xs font-mono overflow-x-auto max-h-64 border border-slate-800">
                    {(() => {
                      try {
                        return JSON.stringify(JSON.parse(selectedLog.responseData), null, 2);
                      } catch {
                        return selectedLog.responseData || JSON.stringify(selectedLog, null, 2);
                      }
                    })()}
                  </pre>
                </div>
              </div>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}
