'use client';

import { useState, useEffect, useCallback } from 'react';
import { paymentVerificationService, type PaymentVerification, type PaymentVerificationStatus } from '@/services/payment-verification.service';
import { adminService } from '@/services/admin.service';
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, Eye, X, Loader2, ChevronLeft, ChevronRight,
  ShieldCheck, User, DollarSign, Image as ImageIcon,
} from 'lucide-react';

type StatusFilter = 'ALL' | PaymentVerificationStatus;

const STATUS_COLORS: Record<string, string> = {
  PENDING: 'bg-amber-500/20 text-amber-300',
  UNDER_REVIEW: 'bg-blue-500/20 text-blue-300',
  APPROVED: 'bg-emerald-500/20 text-emerald-300',
  REJECTED: 'bg-red-500/20 text-red-300',
  EXPIRED: 'bg-slate-500/20 text-slate-300',
};

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

  const handleConfirm = () => {
    if (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 || (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 VerificationDetailModal({ verification, onClose, onRefresh }: { verification: PaymentVerification; onClose: () => void; onRefresh: () => void }) {
  const [actionLoading, setActionLoading] = useState(false);
  const [actionError, setActionError] = useState<string | null>(null);
  const [showConfirm, setShowConfirm] = useState<'approve' | 'reject' | 'request-proof' | null>(null);
  const [confirmNotes, setConfirmNotes] = useState('');

  const handleAction = async () => {
    if (!showConfirm) return;
    setActionLoading(true);
    setActionError(null);
    try {
      if (showConfirm === 'approve') {
        await paymentVerificationService.approveVerification(verification.id, confirmNotes);
      } else if (showConfirm === 'reject') {
        await paymentVerificationService.rejectVerification(verification.id, confirmNotes);
      } else if (showConfirm === 'request-proof') {
        await paymentVerificationService.requestMoreProof(verification.id, confirmNotes);
      }
      onRefresh();
      onClose();
    } catch (err: any) {
      setActionError(err?.message || 'Action failed');
    } finally {
      setActionLoading(false);
      setShowConfirm(null);
      setConfirmNotes('');
    }
  };

  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-2xl 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">Payment Verification Details</h2>
            <p className="text-sm text-slate-400">ID: {verification.id}</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-4">
          {actionError && <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">{actionError}</div>}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p className="text-xs text-slate-400">User ID</p>
              <p className="text-sm text-white">{verification.userId}</p>
            </div>
            <div>
              <p className="text-xs text-slate-400">Payment Type</p>
              <p className="text-sm text-white">{verification.paymentType}</p>
            </div>
            <div>
              <p className="text-xs text-slate-400">Required Amount</p>
              <p className="text-sm text-white">{verification.requiredAmount} {verification.currency}</p>
            </div>
            <div>
              <p className="text-xs text-slate-400">Submitted Amount</p>
              <p className="text-sm text-white">{verification.submittedAmount} {verification.currency}</p>
            </div>
            <div>
              <p className="text-xs text-slate-400">Transaction Hash</p>
              <p className="text-sm text-white font-mono">{verification.transactionHash || '-'}</p>
            </div>
            <div>
              <p className="text-xs text-slate-400">Network</p>
              <p className="text-sm text-white">{verification.network}</p>
            </div>
            <div>
              <p className="text-xs text-slate-400">Wallet Address</p>
              <p className="text-sm text-white font-mono">{verification.walletAddress}</p>
            </div>
            <div>
              <p className="text-xs text-slate-400">Status</p>
              <span className={cn('rounded-full px-2 py-1 text-xs', STATUS_COLORS[verification.status] || 'bg-slate-500/20 text-slate-300')}>{verification.status}</span>
            </div>
            <div>
              <p className="text-xs text-slate-400">Submitted At</p>
              <p className="text-sm text-white">{formatDateTime(verification.submittedAt)}</p>
            </div>
            {verification.reviewedAt && (
              <div>
                <p className="text-xs text-slate-400">Reviewed At</p>
                <p className="text-sm text-white">{formatDateTime(verification.reviewedAt)}</p>
              </div>
            )}
            {verification.reviewReason && (
              <div className="md:col-span-2">
                <p className="text-xs text-slate-400">Review Reason</p>
                <p className="text-sm text-white">{verification.reviewReason}</p>
              </div>
            )}
            {verification.proof && (
              <div className="md:col-span-2">
                <p className="text-xs text-slate-400">Proof</p>
                <a href={verification.proof} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 text-sm text-blue-400 hover:underline">
                  <ImageIcon className="h-4 w-4" />
                  View Proof
                </a>
              </div>
            )}
          </div>
        </div>
        {['PENDING', 'UNDER_REVIEW'].includes(verification.status as string) && (
          <div className="flex justify-end gap-3 border-t border-white/10 p-5 shrink-0">
            <button onClick={() => setShowConfirm('reject')} 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">
              <XCircle className="mr-2 inline h-4 w-4" />
              Reject
            </button>
            <button onClick={() => setShowConfirm('request-proof')} className="rounded-lg border border-amber-500/30 bg-amber-500/10 px-4 py-2 text-sm font-semibold text-amber-300 hover:bg-amber-500/20">
              Request More Proof
            </button>
            <button onClick={() => setShowConfirm('approve')} 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">
              <CheckCircle2 className="mr-2 inline h-4 w-4" />
              Approve
            </button>
          </div>
        )}
        {showConfirm && (
          <ConfirmDialog
            title={showConfirm === 'approve' ? 'Approve Payment' : showConfirm === 'reject' ? 'Reject Payment' : 'Request More Proof'}
            description={showConfirm === 'approve' ? 'This will approve the payment and release the hold.' : showConfirm === 'reject' ? 'This will reject the payment and keep the hold.' : 'The user will be notified to provide more proof.'}
            confirmLabel={showConfirm === 'approve' ? 'Approve' : showConfirm === 'reject' ? 'Reject' : 'Request Proof'}
            confirmVariant={showConfirm === 'approve' ? 'primary' : showConfirm === 'reject' ? 'danger' : 'warning'}
            onConfirm={handleAction}
            onClose={() => { setShowConfirm(null); setConfirmNotes(''); }}
            loading={actionLoading}
            notesField
            notesLabel="Reason / Message"
            notesPlaceholder="Enter reason for this action..."
          />
        )}
      </div>
    </div>
  );
}

export default function SuperAdminPaymentVerificationsPage() {
  const [verifications, setVerifications] = useState<PaymentVerification[]>([]);
  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 [selectedVerification, setSelectedVerification] = useState<PaymentVerification | null>(null);
  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 res = await paymentVerificationService.listVerifications({
        limit: 20,
        offset: (pageNum - 1) * 20,
        sortBy: sortBy ?? undefined,
        sortOrder: sortOrder ?? undefined,
      });
      setVerifications(res.data || []);
      setMeta(res.meta ? { ...res.meta, page: pageNum, totalPages: Math.ceil(res.meta.total / res.meta.limit) } as any : null);
    } catch (err: any) {
      setError(err?.message || 'Failed to load verifications');
    } finally {
      setLoading(false);
    }
  }, [sortBy, sortOrder]);

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

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

  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-blue-500/20 text-blue-300">
            <User className="h-4 w-4" />
          </div>
          <div>
            <p className="text-white">{row.userName}</p>
            <p className="text-xs text-slate-400">{val}</p>
          </div>
        </div>
      ),
    },
    {
      key: 'paymentType',
      label: 'Payment Type',
      sortable: true,
      render: (val: any) => <span className="text-slate-300">{val}</span>,
    },
    {
      key: 'requiredAmount',
      label: 'Required Amount',
      sortable: true,
      render: (val: any, row: any) => <span className="text-slate-300">{val} {row.currency}</span>,
    },
    {
      key: 'submittedAmount',
      label: 'Submitted Amount',
      sortable: true,
      render: (val: any, row: any) => <span className="text-slate-300">{val} {row.currency}</span>,
    },
    {
      key: 'status',
      label: 'Status',
      sortable: true,
      render: (val: any) => (
        <span className={cn('rounded-full px-2 py-1 text-xs', STATUS_COLORS[val] || 'bg-slate-500/20 text-slate-300')}>
          {val}
        </span>
      ),
    },
    {
      key: 'transactionHash',
      label: 'Transaction Hash',
      sortable: true,
      render: (val: any) => <span className="font-mono text-xs">{val ? val.slice(0, 16) + '...' : '-'}</span>,
    },
    {
      key: 'submittedAt',
      label: 'Submitted At',
      sortable: true,
      render: (val: any) => <span className="whitespace-nowrap">{formatDateTime(val)}</span>,
    },
    {
      key: 'reviewedAt',
      label: 'Reviewed At',
      sortable: true,
      render: (val: any) => <span className="whitespace-nowrap">{val ? formatDateTime(val) : '-'}</span>,
    },
    {
      key: 'actions',
      label: 'Actions',
      sortable: false,
      render: (_: any, row: any) => (
        <div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
          {['PENDING', 'UNDER_REVIEW'].includes(row.status as string) && (
            <button
              onClick={() => setSelectedVerification(row)}
              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"
            >
              Review
            </button>
          )}
          <button
            onClick={() => setSelectedVerification(row)}
            className="rounded-lg p-1 text-blue-400 hover:bg-blue-500/10"
          >
            <Eye className="h-4 w-4" />
          </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">
        <div>
          <h1 className="text-2xl font-bold text-white">Payment Verifications</h1>
          <p className="text-sm text-slate-400">Review and approve/reject payment submissions for fines and subscriptions</p>
        </div>
        <button onClick={() => loadVerifications(page)} className="rounded-lg border border-white/10 p-2 text-slate-300 hover:bg-white/5">
          <RefreshCw className={cn('h-5 w-5', loading && 'animate-spin')} />
        </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">{error}</div>}
      {actionError && <div className="rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">{actionError}</div>}
      {actionSuccess && <div className="rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-400">{actionSuccess}</div>}

      <div className="rounded-xl border border-white/10 bg-slate-900/50 overflow-hidden">
        {loading ? (
          <TableSkeleton rows={10} />
        ) : tableData.length === 0 ? (
          <EmptyState message="No payment verifications" description="Payment verifications will appear here when users submit payments." />
        ) : (
          <SortableTable
            data={tableData}
            columns={columns}
            onRowClick={(v) => setSelectedVerification(v)}
            sortBy={sortBy}
            sortOrder={sortOrder}
            onSortChange={handleSortChange}
          />
        )}
      </div>

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

      {selectedVerification && (
        <VerificationDetailModal
          verification={selectedVerification}
          onClose={() => setSelectedVerification(null)}
          onRefresh={() => loadVerifications(page)}
        />
      )}
    </div>
  );
}
