'use client';

import { useState, useEffect, useCallback } from 'react';
import { appealsService, type Appeal, type AppealScenario, type AppealStatus, type AppealResolutionAction } from '@/services/appeals.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,
  User, Gavel, MessageSquare, Search, AlertTriangle,
  FileText, Video,
} from 'lucide-react';

const SCENARIO_LABELS: Record<AppealScenario, string> = {
  PAYMENT_ISSUE: 'Payment Issue',
  BALANCE_DISPUTE: 'Balance Dispute',
  REFERRAL_FREEZE_DISPUTE: 'Referral Freeze Dispute',
  OTHER: 'Other',
  BUYER_PAYMENT_ISSUE: 'Buyer Payment Issue',
  SELLER_PAYMENT_NOT_RECEIVED: 'Seller Payment Not Received',
  BALANCE_DEDUCTION_DISPUTE: 'Balance Deduction Dispute',
};

const STATUS_COLORS: Record<string, string> = {
  OPEN: 'bg-amber-500/20 text-amber-300',
  RESOLVED_COMPLETED: 'bg-emerald-500/20 text-emerald-300',
  RESOLVED_REJECTED: 'bg-red-500/20 text-red-300',
  DISMISSED: 'bg-slate-500/20 text-slate-300',
  REQUEST_MORE_PROOF: 'bg-blue-500/20 text-blue-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 AppealDetailModal({ appeal, onClose, onRefresh }: { appeal: Appeal; 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 [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [confirmType, setConfirmType] = useState<'complete' | 'reject' | 'request-proof' | 'dismiss' | null>(null);
  const [confirmNotes, setConfirmNotes] = useState('');

  const handleAction = async (notes: string) => {
    if (!confirmType) return;
    setActionLoading(true);
    setActionError(null);
    setActionSuccess(null);
    try {
      if (confirmType === 'complete') {
        await appealsService.resolveAppeal(appeal.id, { action: 'COMPLETED', adminNotes: notes });
        setActionSuccess('Appeal completed successfully');
      } else if (confirmType === 'reject') {
        await appealsService.resolveAppeal(appeal.id, { action: 'REJECTED', adminNotes: notes });
        setActionSuccess('Appeal rejected');
      } else if (confirmType === 'request-proof') {
        await appealsService.requestMoreProof(appeal.id, notes);
        setActionSuccess('Request for more proof sent to user');
      } else if (confirmType === 'dismiss') {
        await appealsService.dismissAppeal(appeal.id, notes);
        setActionSuccess('Appeal dismissed');
      }
      onRefresh();
      setTimeout(() => onClose(), 600);
    } catch (err: any) {
      setActionError(err?.message || 'Action failed');
    } finally {
      setActionLoading(false);
      setConfirmType(null);
      setConfirmNotes('');
    }
  };

  const displayName = appeal.user ? `${appeal.user.firstName || ''} ${appeal.user.lastName || ''}`.trim() || appeal.user.email : appeal.userId;

  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">Appeal Details</h2>
            <p className="text-sm text-slate-400">{displayName} &middot; {SCENARIO_LABELS[appeal.scenario]}</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">
            <div>
              <p className="text-xs text-slate-400">Appeal ID</p>
              <p className="text-sm text-white font-mono">{appeal.id}</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[appeal.status] || 'bg-slate-500/20 text-slate-300')}>{appeal.status.replace(/_/g, ' ')}</span>
            </div>
            <div>
              <p className="text-xs text-slate-400">Priority</p>
              <span className={cn('rounded-full px-2 py-1 text-xs', appeal.priority === 'URGENT' ? 'bg-red-500/20 text-red-300' : 'bg-slate-500/20 text-slate-300')}>{appeal.priority}</span>
            </div>
            <div>
              <p className="text-xs text-slate-400">Submitted At</p>
              <p className="text-sm text-white">{formatDateTime(appeal.createdAt)}</p>
            </div>
            {appeal.orderId && (
              <div>
                <p className="text-xs text-slate-400">Order ID</p>
                <p className="text-sm text-white font-mono">{appeal.orderId}</p>
              </div>
            )}
            {appeal.tradeId && (
              <div>
                <p className="text-xs text-slate-400">Trade ID</p>
                <p className="text-sm text-white font-mono">{appeal.tradeId}</p>
              </div>
            )}
            <div className="md:col-span-2">
              <p className="text-xs text-slate-400">Reason</p>
              <p className="text-sm text-white">{appeal.reason}</p>
            </div>
            <div className="md:col-span-2">
              <p className="text-xs text-slate-400">Description</p>
              <p className="text-sm text-white whitespace-pre-wrap">{appeal.description}</p>
            </div>
            {appeal.isSuspicious && (
              <div className="md:col-span-2">
                <p className="text-xs text-slate-400">Suspicious Flag</p>
                <div className="flex items-center gap-2 rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2">
                  <AlertTriangle className="h-4 w-4 text-red-400" />
                  <span className="text-sm text-red-300">{appeal.suspiciousReason || 'Flagged as suspicious'}</span>
                </div>
              </div>
            )}
            {appeal.scenarioData && Object.keys(appeal.scenarioData).length > 0 && (
              <div className="md:col-span-2">
                <p className="text-xs text-slate-400">Scenario Data</p>
                <pre className="text-xs text-slate-300 whitespace-pre-wrap font-mono bg-white/5 p-3 rounded-lg max-h-32 overflow-y-auto">
                  {JSON.stringify(appeal.scenarioData, null, 2)}
                </pre>
              </div>
            )}
          </div>
          {appeal.evidence.length > 0 && (
            <div>
              <p className="text-xs font-medium uppercase text-slate-400 mb-2">Evidence Files</p>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                {appeal.evidence.map((ev) => (
                  <div key={ev.id} className="rounded-lg border border-white/10 overflow-hidden cursor-pointer group" onClick={() => { setSelectedImage(ev.url); setShowImageModal(true); }}>
                    {ev.type === 'IMAGE' ? (
                      <div className="relative aspect-video bg-white/5">
                        <img src={ev.url} alt={ev.filename} className="w-full h-full object-cover" />
                        <div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity">
                          <Eye className="h-6 w-6 text-white" />
                        </div>
                      </div>
                    ) : ev.type === 'VIDEO' ? (
                      <div className="relative aspect-video bg-white/5 flex items-center justify-center">
                        <Video className="h-10 w-10 text-slate-400" />
                      </div>
                    ) : (
                      <div className="flex items-center gap-2 p-3 bg-white/5">
                        <FileText className="h-5 w-5 text-slate-400" />
                        <span className="text-xs text-slate-300 truncate">{ev.filename}</span>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
        {['OPEN', 'REQUEST_MORE_PROOF'].includes(appeal.status) && (
          <div className="flex items-center justify-end gap-3 border-t border-white/10 p-5 shrink-0">
            <button onClick={() => { setConfirmNotes(''); setConfirmType('dismiss'); }} className="rounded-lg border border-slate-500/30 bg-slate-500/10 px-4 py-2 text-sm font-semibold text-slate-300 hover:bg-slate-500/20">
              Dismiss
            </button>
            <button onClick={() => { setConfirmNotes(''); setConfirmType('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={() => { setConfirmNotes(''); setConfirmType('request-proof'); }} 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">
              <MessageSquare className="mr-2 inline h-4 w-4" />
              Request More Proof
            </button>
            <button onClick={() => { setConfirmNotes(''); setConfirmType('complete'); }} 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" />
              Complete
            </button>
          </div>
        )}
        {confirmType && (
          <ConfirmDialog
            title={confirmType === 'complete' ? 'Complete Appeal' : confirmType === 'reject' ? 'Reject Appeal' : confirmType === 'dismiss' ? 'Dismiss Appeal' : 'Request More Proof'}
            description={confirmType === 'complete' ? 'This will approve the appeal and mark it as completed.' : confirmType === 'reject' ? 'This will reject the appeal.' : confirmType === 'dismiss' ? 'This will dismiss the appeal without resolution.' : 'The user will be notified to provide more evidence.'}
            confirmLabel={confirmType === 'complete' ? 'Complete' : confirmType === 'reject' ? 'Reject' : confirmType === 'dismiss' ? 'Dismiss' : 'Request Proof'}
            confirmVariant={confirmType === 'complete' ? 'primary' : confirmType === 'reject' || confirmType === 'dismiss' ? 'danger' : 'warning'}
            onConfirm={handleAction}
            onClose={() => { setConfirmType(null); setConfirmNotes(''); }}
            loading={actionLoading}
            notesField
            notesLabel="Admin Notes"
            notesPlaceholder="Enter notes for this action..."
          />
        )}
        {showImageModal && selectedImage && (
          <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/80 p-8" onClick={() => setShowImageModal(false)}>
            <img src={selectedImage} alt="Evidence 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>
  );
}

export default function SuperAdminAppealsPage() {
  const [appeals, setAppeals] = useState<Appeal[]>([]);
  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 [selectedAppeal, setSelectedAppeal] = useState<Appeal | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('ALL');
  const [sortBy, setSortBy] = useState<string | null>(null);
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc' | null>(null);

  const loadAppeals = useCallback(async (pageNum: number) => {
    setLoading(true);
    setError(null);
    try {
      const res = await appealsService.listAppeals({
        status: statusFilter === 'ALL' ? undefined : (statusFilter as AppealStatus),
        search: searchQuery || undefined,
        limit: 20,
        offset: (pageNum - 1) * 20,
        sortBy: sortBy ?? undefined,
        sortOrder: sortOrder ?? undefined,
      });
      setAppeals(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 appeals');
    } finally {
      setLoading(false);
    }
  }, [statusFilter, searchQuery, sortBy, sortOrder]);

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

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

  const columns: SortableColumn[] = [
    {
      key: 'userEmail',
      label: 'Requester',
      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: 'scenario',
      label: 'Scenario',
      sortable: true,
      render: (val: any) => <span className="text-slate-300">{SCENARIO_LABELS[val as AppealScenario] || val}</span>,
    },
    {
      key: 'reason',
      label: 'Reason',
      sortable: false,
      render: (val: any) => <span className="text-slate-300 truncate max-w-xs block">{val}</span>,
    },
    {
      key: 'priority',
      label: 'Priority',
      sortable: true,
      render: (val: any) => (
        <span className={cn('rounded-full px-2 py-1 text-xs', val === 'URGENT' ? 'bg-red-500/20 text-red-300' : 'bg-slate-500/20 text-slate-300')}>
          {val === 'URGENT' && <AlertTriangle className="mr-1 inline h-3 w-3" />}
          {val}
        </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.replace(/_/g, ' ')}
        </span>
      ),
    },
    {
      key: 'createdAt',
      label: 'Created 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={() => setSelectedAppeal(row)} disabled={actionError !== 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>
        </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">Appeals Management</h1>
          <p className="text-slate-400">Review and resolve user appeals</p>
        </div>
        <button onClick={() => loadAppeals(page)} 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={() => loadAppeals(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 flex-wrap 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, reason..." value={searchQuery} onChange={(e) => { setSearchQuery(e.target.value); setPage(1); }} 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>
        <select value={statusFilter} onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }} className="rounded-lg border border-white/10 bg-white/5 px-4 py-2 text-sm text-white">
          <option value="ALL">All Statuses</option>
          <option value="OPEN">Open</option>
          <option value="RESOLVED_COMPLETED">Resolved Completed</option>
          <option value="RESOLVED_REJECTED">Resolved Rejected</option>
          <option value="DISMISSED">Dismissed</option>
          <option value="REQUEST_MORE_PROOF">More Proof Requested</option>
        </select>
      </div>

      {loading ? (
        <TableSkeleton rows={8} />
      ) : filteredAppeals.length === 0 ? (
        <EmptyState message="No appeals found" description={searchQuery ? 'No results match your search.' : 'There are no appeals to display.'} icon={<Gavel className="h-6 w-6" />} />
      ) : (
        <div className="rounded-xl border border-white/10 bg-slate-900/50 overflow-hidden">
          <SortableTable data={filteredAppeals} columns={columns} onRowClick={(v) => setSelectedAppeal(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">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>
      )}

      {selectedAppeal && (
        <AppealDetailModal appeal={selectedAppeal} onClose={() => setSelectedAppeal(null)} onRefresh={() => loadAppeals(page)} />
      )}
    </div>
  );
}
