'use client';

import { useState, useEffect, useCallback } from 'react';
import { adminService } from '@/services/admin.service';
import type { PendingRegistrationVerification } from '@/types/admin.types';
import { cn, formatDateTime } from '@/lib/utils';
import { TableSkeleton } from '@/components/priority/skeletons';
import { SortableTable, type SortableColumn } from '@/components/tables/SortableTable';
import EmptyState from '@/components/EmptyState';
import {
  RefreshCw,
  CheckCircle2,
  XCircle,
  X,
  Loader2,
  ChevronLeft,
  ChevronRight,
  ShieldCheck,
  User,
  Eye,
  MessageSquare,
  Image as ImageIcon,
  FileText,
  Briefcase,
  DollarSign,
  Mail,
  Hash,
  Search,
} from 'lucide-react';

const MATCH_COLORS: Record<string, string> = {
  MATCHED: 'bg-emerald-500/20 text-emerald-300',
  PARTIAL: 'bg-amber-500/20 text-amber-300',
  NO_MATCH: 'bg-red-500/20 text-red-300',
};

function ConfirmDialog({
  title,
  description,
  confirmLabel,
  confirmVariant = 'danger',
  onConfirm,
  onClose,
  loading,
  notesField,
  notesLabel,
  notesPlaceholder,
  requireNotes = true,
}: {
  title: string;
  description: string;
  confirmLabel: string;
  confirmVariant?: 'danger' | 'primary' | 'warning';
  onConfirm: (notes: string) => void;
  onClose: () => void;
  loading?: boolean;
  notesField?: boolean;
  notesLabel?: string;
  notesPlaceholder?: string;
  requireNotes?: boolean;
}) {
  const [notes, setNotes] = useState('');

  const handleConfirm = () => {
    if (requireNotes && notesField && !notes.trim()) return;
    onConfirm(notes.trim());
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>
      <div className="w-full max-w-lg rounded-xl border border-white/10 bg-slate-900 shadow-2xl" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-white/10 p-5">
          <h2 className="text-lg font-semibold text-white">{title}</h2>
          <button onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:text-white">
            <X className="h-5 w-5" />
          </button>
        </div>
        <div className="p-5">
          <p className="text-sm text-slate-400">{description}</p>
          {notesField && (
            <div className="mt-4">
              <label className="mb-1 block text-sm font-medium text-slate-300">{notesLabel || 'Reason'}</label>
              <textarea
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder={notesPlaceholder || 'Provide a reason...'}
                rows={3}
                className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none resize-none"
              />
            </div>
          )}
        </div>
        <div className="flex justify-end gap-3 border-t border-white/10 p-5">
          <button
            onClick={onClose}
            className="rounded-lg border border-white/10 px-4 py-2 text-sm text-slate-300 hover:bg-white/5"
          >
            Cancel
          </button>
          <button
            onClick={handleConfirm}
            disabled={Boolean(loading || (requireNotes && notesField && !notes.trim()))}
            className={cn(
              'rounded-lg px-4 py-2 text-sm font-semibold text-white disabled:opacity-50',
              confirmVariant === 'danger' && 'bg-red-600 hover:bg-red-700',
              confirmVariant === 'primary' && 'bg-blue-600 hover:bg-blue-700',
              confirmVariant === 'warning' && 'bg-amber-600 hover:bg-amber-700',
            )}
          >
            {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
}

function DetailModal({
  verification,
  onClose,
  onRefresh,
}: {
  verification: PendingRegistrationVerification;
  onClose: () => void;
  onRefresh: () => void;
}) {
  const [actionLoading, setActionLoading] = useState(false);
  const [actionError, setActionError] = useState<string | null>(null);
  const [actionSuccess, setActionSuccess] = useState<string | null>(null);
  const [showImageModal, setShowImageModal] = useState(false);
  const [confirmType, setConfirmType] = useState<'verify' | 'decline' | 'message' | null>(null);
  const [declineReason, setDeclineReason] = useState('');
  const [messageText, setMessageText] = useState('');

  const handleAction = async (notes: string) => {
    if (!confirmType) return;
    setActionLoading(true);
    setActionError(null);
    setActionSuccess(null);
    try {
      if (confirmType === 'verify') {
        await adminService.verifyRegistration(verification.id, { userId: verification.userId, message: notes || undefined });
        setActionSuccess('User verified and account activated successfully');
        onRefresh();
        setTimeout(() => onClose(), 800);
      } else if (confirmType === 'decline') {
        await adminService.declineRegistration(verification.id, { userId: verification.userId, reason: notes, reasonText: notes });
        setActionSuccess('User account terminated successfully');
        onRefresh();
        setTimeout(() => onClose(), 800);
      } else if (confirmType === 'message') {
        await adminService.sendMessageToUser({ userId: verification.userId, message: notes });
        setActionSuccess('Message sent to user successfully');
        setMessageText('');
      }
    } catch (err: any) {
      setActionError(err?.message || 'Action failed');
    } finally {
      setActionLoading(false);
      setConfirmType(null);
    }
  };

  const displayName = [verification.firstName, verification.lastName].filter(Boolean).join(' ') || 'N/A';

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={onClose}>
      <div className="w-full max-w-3xl rounded-xl border border-white/10 bg-slate-900 shadow-2xl max-h-[90vh] overflow-hidden flex flex-col" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-white/10 p-5 shrink-0">
          <div>
            <h2 className="text-lg font-semibold text-white">Registration Verification Details</h2>
            <p className="text-sm text-slate-400">{displayName} &middot; {verification.email}</p>
          </div>
          <button onClick={onClose} className="rounded-lg p-1 text-slate-400 hover:text-white">
            <X className="h-5 w-5" />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-5 space-y-5">
          {actionError && (
            <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400 flex items-center justify-between">
              <span>{actionError}</span>
              <button onClick={() => setActionError(null)} className="ml-4 text-red-300 hover:text-white">&times;</button>
            </div>
          )}
          {actionSuccess && (
            <div className="rounded-lg border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-400 flex items-center gap-2">
              <CheckCircle2 className="h-4 w-4" />
              {actionSuccess}
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <DetailField label="Email" value={verification.email} />
            <DetailField label="Job Title" value={verification.jobTitle || 'N/A'} icon={<Briefcase className="h-3.5 w-3.5" />} />
            <DetailField label="Income Range" value={verification.incomeRange || 'N/A'} icon={<DollarSign className="h-3.5 w-3.5" />} />
            <DetailField label="Verification Code" value={verification.verificationCode || 'N/A'} icon={<Hash className="h-3.5 w-3.5" />} />
            <DetailField label="Recipient Email" value={verification.recipientEmail || 'N/A'} icon={<Mail className="h-3.5 w-3.5" />} />
            <DetailField
              label="OCR Match Status"
              value={
                <span className={cn('rounded-full px-2 py-0.5 text-xs font-medium', MATCH_COLORS[verification.ocrMatchStatus] || 'bg-slate-500/20 text-slate-300')}>
                  {verification.ocrMatchStatus}
                </span>
              }
            />
            {verification.ocrConfidence !== null && verification.ocrConfidence !== undefined && (
              <DetailField label="OCR Confidence" value={`${verification.ocrConfidence.toFixed(1)}%`} />
            )}
            <DetailField label="Submitted" value={formatDateTime(verification.createdAt)} />
            <DetailField label="Status" value={verification.status} />
          </div>

          {verification.screenshotUrl && (
            <div>
              <p className="text-xs font-medium uppercase text-slate-400 mb-2">Screenshot</p>
              <div className="relative inline-block rounded-lg border border-white/10 overflow-hidden cursor-pointer group" onClick={() => setShowImageModal(true)}>
                <img
                  src={verification.screenshotUrl}
                  alt="Verification screenshot"
                  className="max-h-48 max-w-full object-contain bg-white/5"
                />
                <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity">
                  <div className="flex items-center gap-2 rounded-full bg-white/10 px-3 py-1.5 text-xs text-white backdrop-blur-sm">
                    <Eye className="h-4 w-4" />
                    View Full Image
                  </div>
                </div>
              </div>
            </div>
          )}

          {verification.ocrExtractedText && (
            <div>
              <p className="text-xs font-medium uppercase text-slate-400 mb-2 flex items-center gap-1.5">
                <FileText className="h-3.5 w-3.5" />
                OCR Extracted Text
              </p>
              <div className="rounded-lg border border-white/10 bg-white/5 p-4">
                <pre className="text-xs text-slate-300 whitespace-pre-wrap font-mono leading-relaxed max-h-48 overflow-y-auto">
                  {verification.ocrExtractedText}
                </pre>
              </div>
            </div>
          )}
        </div>

        {verification.status === 'PENDING' && (
          <div className="flex items-center justify-between border-t border-white/10 p-5 shrink-0 gap-3">
            <div className="flex items-center gap-2">
              <button
                onClick={() => { setDeclineReason(''); setConfirmType('decline'); }}
                className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2 text-sm font-semibold text-red-300 hover:bg-red-500/20 flex items-center gap-1.5"
              >
                <XCircle className="h-4 w-4" />
                Decline
              </button>
              <button
                onClick={() => { setMessageText(''); setConfirmType('message'); }}
                className="rounded-lg border border-blue-500/30 bg-blue-500/10 px-4 py-2 text-sm font-semibold text-blue-300 hover:bg-blue-500/20 flex items-center gap-1.5"
              >
                <MessageSquare className="h-4 w-4" />
                Send Message
              </button>
            </div>
            <button
              onClick={() => { setDeclineReason(''); setConfirmType('verify'); }}
              className="rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-4 py-2 text-sm font-semibold text-emerald-300 hover:bg-emerald-500/20 flex items-center gap-1.5"
            >
              <CheckCircle2 className="h-4 w-4" />
              Verify &amp; Activate
            </button>
          </div>
        )}

        {confirmType === 'verify' && (
          <ConfirmDialog
            title="Verify & Activate Account"
            description={`This will verify the registration for ${verification.email} and activate their account.`}
            confirmLabel="Verify & Activate"
            confirmVariant="primary"
            onConfirm={handleAction}
            onClose={() => setConfirmType(null)}
            loading={actionLoading}
            notesField={false}
            requireNotes={false}
          />
        )}

        {confirmType === 'decline' && (
          <ConfirmDialog
            title="Decline & Terminate Account"
            description={`This will decline the registration for ${verification.email} AND terminate the user account. This action cannot be undone.`}
            confirmLabel="Decline & Terminate"
            confirmVariant="danger"
            onConfirm={handleAction}
            onClose={() => setConfirmType(null)}
            loading={actionLoading}
            notesField
            notesLabel="Decline Reason"
            notesPlaceholder="Provide a reason for declining this verification..."
          />
        )}

        {confirmType === 'message' && (
          <ConfirmDialog
            title="Send Message to User"
            description={`Send a custom message to ${verification.email}. They will be notified.`}
            confirmLabel="Send Message"
            confirmVariant="primary"
            onConfirm={handleAction}
            onClose={() => setConfirmType(null)}
            loading={actionLoading}
            notesField
            notesLabel="Message"
            notesPlaceholder="Enter your message to the user..."
          />
        )}

        {showImageModal && verification.screenshotUrl && (
          <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/80 p-8" onClick={() => setShowImageModal(false)}>
            <img
              src={verification.screenshotUrl}
              alt="Verification screenshot - full"
              className="max-h-full max-w-full object-contain rounded-lg shadow-2xl"
              onClick={(e) => e.stopPropagation()}
            />
            <button
              onClick={() => setShowImageModal(false)}
              className="absolute top-6 right-6 rounded-lg bg-white/10 p-2 text-white hover:bg-white/20"
            >
              <X className="h-6 w-6" />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

function DetailField({
  label,
  value,
  icon,
}: {
  label: string;
  value: React.ReactNode;
  icon?: React.ReactNode;
}) {
  return (
    <div className="rounded-lg border border-white/10 bg-white/5 p-3">
      <p className="text-xs font-medium uppercase text-slate-400 mb-1 flex items-center gap-1.5">
        {icon}
        {label}
      </p>
      <p className="text-sm text-white break-words">{value}</p>
    </div>
  );
}

function ConfidenceBar({ confidence }: { confidence: number }) {
  const pct = Math.min(100, Math.max(0, confidence));
  const color = pct >= 80 ? 'bg-emerald-500' : pct >= 50 ? 'bg-amber-500' : 'bg-red-500';
  return (
    <div className="flex items-center gap-2">
      <div className="flex-1 h-2 rounded-full bg-white/10 overflow-hidden">
        <div className={cn('h-full rounded-full transition-all', color)} style={{ width: `${pct}%` }} />
      </div>
      <span className="text-xs text-slate-400 w-10 text-right">{pct.toFixed(0)}%</span>
    </div>
  );
}

export default function SuperAdminVerificationsPage() {
  const [verifications, setVerifications] = useState<PendingRegistrationVerification[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [meta, setMeta] = useState<{ total: number; page: number; limit: number; totalPages: number } | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [actionError, setActionError] = useState<string | null>(null);
  const [actionSuccess, setActionSuccess] = useState<string | null>(null);
  const [actionLoadingId, setActionLoadingId] = useState<string | null>(null);
  const [selectedVerification, setSelectedVerification] = useState<PendingRegistrationVerification | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<string | null>(null);
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc' | null>(null);

  const loadVerifications = useCallback(async (pageNum: number) => {
    setLoading(true);
    setError(null);
    try {
      const response = await adminService.listPendingRegistrationVerifications(pageNum, 20);
      setVerifications(response.data);
      setMeta(response.meta);
    } catch (err: any) {
      setError(err?.message || 'Failed to load pending verifications');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadVerifications(page);
  }, [page, loadVerifications]);

  const handleRefresh = () => {
    loadVerifications(page);
  };

  const filteredVerifications = searchQuery.trim()
    ? verifications.filter((v) => {
        const q = searchQuery.toLowerCase();
        return (
          v.email.toLowerCase().includes(q) ||
          (v.firstName && v.firstName.toLowerCase().includes(q)) ||
          (v.lastName && v.lastName.toLowerCase().includes(q)) ||
          (v.jobTitle && v.jobTitle.toLowerCase().includes(q)) ||
          (v.verificationCode && v.verificationCode.toLowerCase().includes(q)) ||
          (v.recipientEmail && v.recipientEmail.toLowerCase().includes(q))
        );
      })
    : verifications;

  const tableData = filteredVerifications.map((v) => ({
    ...v,
    userName: `${v.firstName || ''} ${v.lastName || ''}`.trim() || v.email,
    userEmail: v.email,
  }));

  const columns: SortableColumn[] = [
    {
      key: 'userEmail',
      label: 'User',
      sortable: true,
      render: (val: any, row: any) => (
        <div className="flex items-center gap-2">
          <div className="flex h-8 w-8 items-center justify-center rounded-full bg-white/10 text-slate-300">
            <User className="h-4 w-4" />
          </div>
          <div>
            <p className="text-white font-medium">{row.userName}</p>
            <p className="text-xs text-slate-400">{val}</p>
          </div>
        </div>
      ),
    },
    {
      key: 'jobTitle',
      label: 'Job Title',
      sortable: true,
      render: (val: any) => <span className="text-slate-300">{val || 'N/A'}</span>,
    },
    {
      key: 'incomeRange',
      label: 'Income Range',
      sortable: true,
      render: (val: any) => <span className="text-slate-300">{val || 'N/A'}</span>,
    },
    {
      key: 'verificationCode',
      label: 'Verification Code',
      sortable: true,
      render: (val: any) => <span className="text-slate-300 font-mono text-xs">{val || 'N/A'}</span>,
    },
    {
      key: 'recipientEmail',
      label: 'Recipient Email',
      sortable: true,
      render: (val: any) => <span className="text-slate-300">{val || 'N/A'}</span>,
    },
    {
      key: 'ocrMatchStatus',
      label: 'OCR Match Status',
      sortable: true,
      render: (val: any) => (
        <span className={cn('rounded-full px-2 py-0.5 text-xs font-medium', MATCH_COLORS[val] || 'bg-slate-500/20 text-slate-300')}>
          {val}
        </span>
      ),
    },
    {
      key: 'ocrConfidence',
      label: 'OCR Confidence',
      sortable: true,
      render: (val: any) => (
        <span className="text-slate-300">{val !== null && val !== undefined ? `${val.toFixed(1)}%` : 'N/A'}</span>
      ),
    },
    {
      key: 'createdAt',
      label: 'Submitted At',
      sortable: true,
      render: (val: any) => <span className="whitespace-nowrap">{formatDateTime(val)}</span>,
    },
    {
      key: 'actions',
      label: 'Actions',
      sortable: false,
      render: (_: any, row: any) => (
        <div className="flex items-center justify-end gap-1" onClick={(e) => e.stopPropagation()}>
          <button
            onClick={() => setSelectedVerification(row)}
            disabled={actionLoadingId !== null}
            className="rounded-lg p-1.5 text-blue-400 hover:bg-blue-500/10 disabled:opacity-50"
            title="View Details"
          >
            <Eye className="h-4 w-4" />
          </button>
          <button
            onClick={() => setSelectedVerification(row)}
            disabled={actionLoadingId !== null}
            className="rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-3 py-1.5 text-xs font-medium text-emerald-300 hover:bg-emerald-500/20 disabled:opacity-50 flex items-center gap-1.5"
            title="Verify"
          >
            <CheckCircle2 className="h-3.5 w-3.5" />
            Verify
          </button>
          <button
            onClick={() => setSelectedVerification(row)}
            disabled={actionLoadingId !== null}
            className="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-1.5 text-xs font-medium text-red-300 hover:bg-red-500/20 disabled:opacity-50 flex items-center gap-1.5"
            title="Decline"
          >
            <XCircle className="h-3.5 w-3.5" />
            Decline
          </button>
        </div>
      ),
    },
  ];

  const handleSortChange = (key: string, order: 'asc' | 'desc' | null) => {
    setSortBy(key);
    setSortOrder(order);
    setPage(1);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Registration Verifications</h1>
          <p className="text-slate-400">Review and verify new user registration submissions</p>
        </div>
        <button
          onClick={handleRefresh}
          disabled={loading}
          className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm text-slate-300 hover:bg-white/10 disabled:opacity-50"
        >
          <RefreshCw className={cn('h-4 w-4', loading && 'animate-spin')} />
          Refresh
        </button>
      </div>

      {error && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400 flex items-center justify-between">
          <span>{error}</span>
          <button onClick={() => loadVerifications(page)} className="ml-4 underline hover:text-white">Retry</button>
        </div>
      )}

      {actionError && (
        <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400 flex items-center justify-between">
          <span>{actionError}</span>
          <button onClick={() => setActionError(null)} className="ml-4 text-red-300 hover:text-white">&times;</button>
        </div>
      )}

      {actionSuccess && (
        <div className="rounded-lg border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-400 flex items-center justify-between">
          <span className="flex items-center gap-2">
            <CheckCircle2 className="h-4 w-4" />
            {actionSuccess}
          </span>
          <button onClick={() => setActionSuccess(null)} className="ml-4 text-green-300 hover:text-white">&times;</button>
        </div>
      )}

      <div className="flex items-center gap-3">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            placeholder="Search by email, name, code..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full rounded-lg border border-white/10 bg-white/5 pl-10 pr-4 py-2 text-sm text-white placeholder:text-slate-400 focus:border-blue-500 focus:outline-none"
          />
        </div>
      </div>

      {loading ? (
        <TableSkeleton rows={8} />
      ) : tableData.length === 0 ? (
        <EmptyState
          message="No pending verifications"
          description={searchQuery ? 'No results match your search.' : 'All registration submissions have been reviewed.'}
          icon={<ShieldCheck className="h-6 w-6" />}
        />
      ) : (
        <SortableTable
          data={tableData}
          columns={columns}
          onRowClick={(v) => setSelectedVerification(v)}
          sortBy={sortBy}
          sortOrder={sortOrder}
          onSortChange={handleSortChange}
        />
      )}

      {meta && meta.totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-slate-400">
            Showing {((meta.page - 1) * meta.limit) + 1} to {Math.min(meta.page * meta.limit, meta.total)} of {meta.total} results
          </p>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={meta.page <= 1 || loading}
              className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-slate-300 hover:bg-white/10 disabled:opacity-50"
            >
              <ChevronLeft className="h-4 w-4" />
              Previous
            </button>
            <span className="text-sm text-slate-400">
              Page {meta.page} of {meta.totalPages}
            </span>
            <button
              onClick={() => setPage((p) => Math.min(meta.totalPages, p + 1))}
              disabled={meta.page >= meta.totalPages || loading}
              className="inline-flex items-center gap-1 rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm text-slate-300 hover:bg-white/10 disabled:opacity-50"
            >
              Next
              <ChevronRight className="h-4 w-4" />
            </button>
          </div>
        </div>
      )}

      {selectedVerification && (
        <DetailModal
          verification={selectedVerification}
          onClose={() => setSelectedVerification(null)}
          onRefresh={handleRefresh}
        />
      )}
    </div>
  );
}
