'use client';

import {
  CheckCircle,
  XCircle,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  FileText,
  ShieldCheck,
  X,
} from 'lucide-react';
import Image from 'next/image';
import { useEffect, useState, useCallback } from 'react';
import { Badge } from '@/components/ui/badge';
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';

function kycStatusBadge(status: string) {
  switch (status) {
    case 'VERIFIED': return <Badge variant="success">Đã xác minh</Badge>;
    case 'PENDING': return <Badge variant="warning">Chờ duyệt</Badge>;
    case 'REJECTED': return <Badge variant="destructive">Bị từ chối</Badge>;
    default: return <Badge variant="secondary">{status}</Badge>;
  }
}

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

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

  return (
    <div className="space-y-4">
      <div className="flex items-start justify-between">
        <div>
          <h3 className="text-lg font-semibold">{item.fullName}</h3>
          <p className="text-sm text-muted-foreground">{item.phone}</p>
          {item.email && (
            <p className="text-sm text-muted-foreground">{item.email}</p>
          )}
        </div>
        {kycStatusBadge(item.kycStatus)}
      </div>

      <div className="grid grid-cols-2 gap-3">
        <div className="rounded-md border p-3">
          <div className="text-xs text-muted-foreground">Vai trò</div>
          <div className="mt-1 text-sm font-medium">{item.role}</div>
        </div>
        <div className="rounded-md border p-3">
          <div className="text-xs text-muted-foreground">Ngày gửi</div>
          <div className="mt-1 text-sm font-medium">
            {new Date(item.createdAt).toLocaleDateString('vi-VN')}
          </div>
        </div>
      </div>

      {kycData && (
        <div className="space-y-3">
          <h4 className="text-sm font-medium">Thông tin KYC</h4>
          {kycData.idType && (
            <div className="rounded-md border p-3">
              <div className="text-xs text-muted-foreground">Loại giấy tờ</div>
              <div className="mt-1 text-sm font-medium">{kycData.idType}</div>
            </div>
          )}
          {kycData.idNumber && (
            <div className="rounded-md border p-3">
              <div className="text-xs text-muted-foreground">Số giấy tờ</div>
              <div className="mt-1 text-sm font-medium">{kycData.idNumber}</div>
            </div>
          )}

          <div className="grid gap-2">
            {kycData.frontImageUrl && (
              <div className="space-y-1">
                <div className="text-xs text-muted-foreground">Mặt trước</div>
                <div className="relative aspect-video overflow-hidden rounded-md border bg-muted">
                  <Image
                    src={kycData.frontImageUrl}
                    alt="Mặt trước giấy tờ"
                    fill
                    sizes="(max-width: 768px) 100vw, 400px"
                    className="object-contain"
                  />
                </div>
              </div>
            )}
            {kycData.backImageUrl && (
              <div className="space-y-1">
                <div className="text-xs text-muted-foreground">Mặt sau</div>
                <div className="relative aspect-video overflow-hidden rounded-md border bg-muted">
                  <Image
                    src={kycData.backImageUrl}
                    alt="Mặt sau giấy tờ"
                    fill
                    sizes="(max-width: 768px) 100vw, 400px"
                    className="object-contain"
                  />
                </div>
              </div>
            )}
            {kycData.selfieUrl && (
              <div className="space-y-1">
                <div className="text-xs text-muted-foreground">Ảnh selfie</div>
                <div className="relative aspect-video overflow-hidden rounded-md border bg-muted">
                  <Image
                    src={kycData.selfieUrl}
                    alt="Selfie"
                    fill
                    sizes="(max-width: 768px) 100vw, 400px"
                    className="object-contain"
                  />
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {item.kycStatus === 'PENDING' && (
        <div className="flex gap-2">
          <Button className="flex-1" onClick={onApprove}>
            <CheckCircle className="mr-2 h-4 w-4" />
            Duyệt KYC
          </Button>
          <Button variant="destructive" className="flex-1" onClick={onReject}>
            <XCircle className="mr-2 h-4 w-4" />
            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);

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

  // Reject dialog
  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="space-y-6">
      {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-2xl font-bold tracking-tight">Duyệt KYC</h1>
          <p className="text-sm text-muted-foreground">
            Xác minh danh tính người dùng và đại lý
          </p>
        </div>
        <Button variant="outline" size="sm" onClick={fetchQueue}>
          <RefreshCw className="mr-2 h-4 w-4" />
          Làm mới
        </Button>
      </div>

      <div className="grid gap-6 lg:grid-cols-[1fr_400px]">
        {/* Table */}
        <Card>
          <CardContent className="p-0">
            {loading ? (
              <div className="flex h-48 items-center justify-center">
                <RefreshCw className="h-5 w-5 animate-spin text-muted-foreground" />
              </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-green-500" />
                <p className="text-sm text-muted-foreground">
                  Không có yêu cầu KYC nào đang chờ
                </p>
              </div>
            ) : (
              <>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Họ tên</TableHead>
                      <TableHead className="hidden sm:table-cell">SĐT</TableHead>
                      <TableHead>Vai trò</TableHead>
                      <TableHead>Trạng thái</TableHead>
                      <TableHead className="hidden md:table-cell">Ngày gửi</TableHead>
                      <TableHead className="w-10"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {result.data.map((item) => (
                      <TableRow
                        key={item.userId}
                        className={`cursor-pointer ${selectedItem?.userId === item.userId ? 'bg-muted/50' : ''}`}
                        onClick={() => setSelectedItem(item)}
                      >
                        <TableCell>
                          <div className="font-medium">{item.fullName}</div>
                          {item.email && (
                            <div className="text-xs text-muted-foreground">{item.email}</div>
                          )}
                        </TableCell>
                        <TableCell className="hidden sm:table-cell">{item.phone}</TableCell>
                        <TableCell>
                          <Badge variant="outline">{item.role}</Badge>
                        </TableCell>
                        <TableCell>{kycStatusBadge(item.kycStatus)}</TableCell>
                        <TableCell className="hidden md:table-cell text-sm text-muted-foreground">
                          {new Date(item.createdAt).toLocaleDateString('vi-VN')}
                        </TableCell>
                        <TableCell>
                          <FileText className="h-4 w-4 text-muted-foreground" />
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>

                {result.totalPages > 1 && (
                  <div className="flex items-center justify-between border-t px-4 py-3">
                    <span className="text-sm text-muted-foreground">
                      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 sidebar */}
        <div className="hidden lg:block">
          <Card>
            <CardContent className="p-4">
              {selectedItem ? (
                <KycDetailView
                  item={selectedItem}
                  onApprove={() => {
                    setApproveDialog(selectedItem.userId);
                    setApproveNotes('');
                  }}
                  onReject={() => {
                    setRejectDialog(selectedItem.userId);
                    setRejectReason('');
                  }}
                />
              ) : (
                <div className="flex h-48 items-center justify-center text-sm text-muted-foreground">
                  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>
  );
}
