'use client';

import {
  CheckCircle,
  XCircle,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  ShieldCheck,
  X,
  User,
} from 'lucide-react';
import Image from 'next/image';
import { useEffect, useState, useCallback } from 'react';
import { StatusChip } from '@/components/design-system/status-chip';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { adminApi, type KycQueueItem, type PaginatedResult } from '@/lib/admin-api';

interface KycData {
  idType?: string;
  idNumber?: string;
  frontImageUrl?: string;
  backImageUrl?: string;
  selfieUrl?: string;
  [key: string]: unknown;
}

function kycStatusToPropertyStatus(status: string): 'active' | 'pending' | 'rejected' {
  if (status === 'VERIFIED') return 'active';
  if (status === 'REJECTED') return 'rejected';
  return 'pending';
}

function KycDetailPanel({ item, onApprove, onReject }: {
  item: KycQueueItem;
  onApprove: () => void;
  onReject: () => void;
}) {
  const kycData = item.kycData as KycData | null;

  return (
    <div className="flex flex-col gap-4 p-4">
      {/* Identity */}
      <div className="flex items-start justify-between gap-2">
        <div>
          <div className="font-semibold text-sm">{item.fullName}</div>
          <div className="text-xs text-foreground-muted mt-0.5">{item.phone}</div>
          {item.email && <div className="text-xs text-foreground-dim">{item.email}</div>}
        </div>
        <StatusChip status={kycStatusToPropertyStatus(item.kycStatus)} />
      </div>

      {/* Meta grid */}
      <div className="grid grid-cols-2 gap-2">
        <div className="rounded-md border border-border bg-background-surface p-2.5">
          <div className="text-xs text-foreground-dim mb-1">Vai trò</div>
          <div className="text-sm font-medium">{item.role}</div>
        </div>
        <div className="rounded-md border border-border bg-background-surface p-2.5">
          <div className="text-xs text-foreground-dim mb-1">Ngày gửi</div>
          <div className="font-mono text-data-sm">{new Date(item.createdAt).toLocaleDateString('vi-VN')}</div>
        </div>
      </div>

      {/* KYC data */}
      {kycData && (
        <div className="flex flex-col gap-3">
          <div className="text-xs font-semibold uppercase tracking-widest text-foreground-dim">Tài liệu KYC</div>

          {(kycData.idType || kycData.idNumber) && (
            <div className="grid grid-cols-2 gap-2">
              {kycData.idType && (
                <div className="rounded border border-border p-2">
                  <div className="text-xs text-foreground-dim">Loại giấy tờ</div>
                  <div className="mt-0.5 text-sm font-medium">{kycData.idType}</div>
                </div>
              )}
              {kycData.idNumber && (
                <div className="rounded border border-border p-2">
                  <div className="text-xs text-foreground-dim">Số giấy tờ</div>
                  <div className="mt-0.5 font-mono text-data-sm">{kycData.idNumber}</div>
                </div>
              )}
            </div>
          )}

          {[
            { url: kycData.frontImageUrl, label: 'Mặt trước CCCD/CMND' },
            { url: kycData.backImageUrl, label: 'Mặt sau CCCD/CMND' },
            { url: kycData.selfieUrl, label: 'Ảnh selfie xác nhận' },
          ].map(({ url, label }) =>
            url ? (
              <div key={label} className="space-y-1">
                <div className="text-xs text-foreground-dim">{label}</div>
                <div className="relative aspect-video overflow-hidden rounded-md border border-border bg-background-surface">
                  <Image
                    src={url}
                    alt={label}
                    fill
                    sizes="(max-width: 768px) 100vw, 380px"
                    className="object-contain"
                  />
                </div>
              </div>
            ) : null,
          )}
        </div>
      )}

      {/* Actions */}
      {item.kycStatus === 'PENDING' && (
        <div className="flex gap-2 pt-1">
          <Button className="flex-1" size="sm" onClick={onApprove}>
            <CheckCircle className="mr-1.5 h-3.5 w-3.5" />
            Duyệt KYC
          </Button>
          <Button variant="destructive" className="flex-1" size="sm" onClick={onReject}>
            <XCircle className="mr-1.5 h-3.5 w-3.5" />
            Từ chối
          </Button>
        </div>
      )}
    </div>
  );
}

export default function AdminKycPage() {
  const [result, setResult] = useState<PaginatedResult<KycQueueItem> | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);

  const [selectedItem, setSelectedItem] = useState<KycQueueItem | null>(null);

  const [approveDialog, setApproveDialog] = useState<string | null>(null);
  const [approveNotes, setApproveNotes] = useState('');

  const [rejectDialog, setRejectDialog] = useState<string | null>(null);
  const [rejectReason, setRejectReason] = useState('');

  const [actionLoading, setActionLoading] = useState(false);
  const [actionError, setActionError] = useState<string | null>(null);

  const fetchQueue = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await adminApi.getKycQueue(page, 20);
      setResult(data);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Không thể tải hàng đợi KYC');
    } finally {
      setLoading(false);
    }
  }, [page]);

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

  const handleApprove = async () => {
    if (!approveDialog) return;
    setActionLoading(true);
    try {
      await adminApi.approveKyc(approveDialog, approveNotes || undefined);
      setApproveDialog(null);
      setApproveNotes('');
      setSelectedItem(null);
      fetchQueue();
    } catch (e) {
      setActionError(e instanceof Error ? e.message : 'Thao tác thất bại. Vui lòng thử lại.');
    } finally {
      setActionLoading(false);
    }
  };

  const handleReject = async () => {
    if (!rejectDialog || !rejectReason.trim()) return;
    setActionLoading(true);
    try {
      await adminApi.rejectKyc(rejectDialog, rejectReason);
      setRejectDialog(null);
      setRejectReason('');
      setSelectedItem(null);
      fetchQueue();
    } catch (e) {
      setActionError(e instanceof Error ? e.message : 'Thao tác thất bại. Vui lòng thử lại.');
    } finally {
      setActionLoading(false);
    }
  };

  return (
    <div className="flex flex-col gap-4">
      {actionError && (
        <div className="flex items-center justify-between rounded-md border border-destructive/50 bg-destructive/10 px-4 py-2 text-sm text-destructive">
          <span>{actionError}</span>
          <button onClick={() => setActionError(null)} className="ml-2">
            <X className="h-4 w-4" />
          </button>
        </div>
      )}

      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-heading-md font-semibold tracking-tight">Duyệt KYC</h1>
          <p className="text-sm text-foreground-muted">Xác minh danh tính người dùng và đại lý</p>
        </div>
        <Button variant="outline" size="sm" onClick={fetchQueue} disabled={loading}>
          <RefreshCw className={`mr-1.5 h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} />
          Làm mới
        </Button>
      </div>

      <div className="grid gap-4 lg:grid-cols-[1fr_400px]">
        {/* Table */}
        <Card className="shadow-elevation-1 overflow-hidden">
          <CardContent className="p-0">
            {loading ? (
              <div className="flex h-48 items-center justify-center">
                <RefreshCw className="h-5 w-5 animate-spin text-foreground-muted" />
              </div>
            ) : error ? (
              <div className="flex h-48 flex-col items-center justify-center gap-2">
                <p className="text-sm text-destructive">{error}</p>
                <Button variant="outline" size="sm" onClick={fetchQueue}>Thử lại</Button>
              </div>
            ) : !result || result.data.length === 0 ? (
              <div className="flex h-48 flex-col items-center justify-center gap-2">
                <ShieldCheck className="h-8 w-8 text-signal-up" />
                <p className="text-sm text-foreground-muted">Không có yêu cầu KYC nào đang chờ</p>
              </div>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader className="sticky top-0 z-sticky-header bg-background-elevated">
                      <TableRow className="border-b border-border-strong">
                        <TableHead className="text-heading-xs uppercase text-foreground-muted">Họ tên</TableHead>
                        <TableHead className="hidden sm:table-cell text-heading-xs uppercase text-foreground-muted">SĐT</TableHead>
                        <TableHead className="text-heading-xs uppercase text-foreground-muted">Vai trò</TableHead>
                        <TableHead className="text-heading-xs uppercase text-foreground-muted">Trạng thái</TableHead>
                        <TableHead className="hidden md:table-cell text-heading-xs uppercase text-foreground-muted">Ngày gửi</TableHead>
                        <TableHead className="w-10"></TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {result.data.map((item) => (
                        <TableRow
                          key={item.userId}
                          onClick={() => setSelectedItem(item)}
                          className={`h-row-compact cursor-pointer border-b border-border transition-colors ${
                            selectedItem?.userId === item.userId
                              ? 'bg-background-surface'
                              : 'hover:bg-background-surface'
                          }`}
                        >
                          <TableCell>
                            <div className="text-sm font-medium">{item.fullName}</div>
                            {item.email && (
                              <div className="text-xs text-foreground-dim">{item.email}</div>
                            )}
                          </TableCell>
                          <TableCell className="hidden sm:table-cell font-mono text-data-sm text-foreground-muted">
                            {item.phone}
                          </TableCell>
                          <TableCell>
                            <span className="rounded-pill bg-background-surface px-2 py-0.5 text-xs font-medium text-foreground-muted ring-1 ring-inset ring-border">
                              {item.role}
                            </span>
                          </TableCell>
                          <TableCell>
                            <StatusChip status={kycStatusToPropertyStatus(item.kycStatus)} />
                          </TableCell>
                          <TableCell className="hidden md:table-cell font-mono text-data-sm text-foreground-dim">
                            {new Date(item.createdAt).toLocaleDateString('vi-VN')}
                          </TableCell>
                          <TableCell>
                            <User className="h-4 w-4 text-foreground-dim" />
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>

                {result.totalPages > 1 && (
                  <div className="flex items-center justify-between border-t border-border px-4 py-2.5">
                    <span className="font-mono text-data-sm text-foreground-muted">
                      Trang {result.page}/{result.totalPages} · {result.total} yêu cầu
                    </span>
                    <div className="flex gap-1">
                      <Button variant="outline" size="icon" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
                        <ChevronLeft className="h-4 w-4" />
                      </Button>
                      <Button variant="outline" size="icon" disabled={page >= result.totalPages} onClick={() => setPage((p) => p + 1)}>
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                )}
              </>
            )}
          </CardContent>
        </Card>

        {/* Detail panel */}
        <div className="hidden lg:block">
          <Card className="shadow-elevation-1 sticky top-20">
            <CardContent className="p-0">
              {selectedItem ? (
                <KycDetailPanel
                  item={selectedItem}
                  onApprove={() => { setApproveDialog(selectedItem.userId); setApproveNotes(''); }}
                  onReject={() => { setRejectDialog(selectedItem.userId); setRejectReason(''); }}
                />
              ) : (
                <div className="flex h-48 items-center justify-center text-sm text-foreground-muted">
                  Chọn yêu cầu KYC để xem chi tiết
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Approve dialog */}
      <Dialog open={!!approveDialog} onOpenChange={() => setApproveDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Duyệt KYC</DialogTitle>
            <DialogDescription>Xác nhận danh tính người dùng đã được xác minh thành công.</DialogDescription>
          </DialogHeader>
          <Input
            placeholder="Ghi chú (không bắt buộc)..."
            value={approveNotes}
            onChange={(e) => setApproveNotes(e.target.value)}
          />
          <DialogFooter>
            <Button variant="outline" onClick={() => setApproveDialog(null)}>Hủy</Button>
            <Button onClick={handleApprove} disabled={actionLoading}>
              {actionLoading ? 'Đang xử lý...' : 'Xác nhận duyệt'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Reject dialog */}
      <Dialog open={!!rejectDialog} onOpenChange={() => setRejectDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Từ chối KYC</DialogTitle>
            <DialogDescription>Vui lòng nhập lý do từ chối. Người dùng sẽ cần gửi lại hồ sơ.</DialogDescription>
          </DialogHeader>
          <Input
            placeholder="Lý do từ chối (bắt buộc)..."
            value={rejectReason}
            onChange={(e) => setRejectReason(e.target.value)}
          />
          <DialogFooter>
            <Button variant="outline" onClick={() => setRejectDialog(null)}>Hủy</Button>
            <Button
              variant="destructive"
              onClick={handleReject}
              disabled={actionLoading || !rejectReason.trim()}
            >
              {actionLoading ? 'Đang xử lý...' : 'Từ chối KYC'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
