'use client';

import {
  CheckCircle,
  XCircle,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  AlertTriangle,
  X,
} from 'lucide-react';
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 ModerationQueueItem, type PaginatedResult } from '@/lib/admin-api';
import { formatPrice } from '@/lib/currency';

function moderationScoreBadge(score: number | null) {
  if (score === null) return <Badge variant="secondary">N/A</Badge>;
  if (score >= 80) return <Badge variant="success">{score}</Badge>;
  if (score >= 50) return <Badge variant="warning">{score}</Badge>;
  return <Badge variant="destructive">{score}</Badge>;
}

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

  // Selected items for bulk
  const [selected, setSelected] = useState<Set<string>>(new Set());

  // Action dialogs
  const [approveDialog, setApproveDialog] = useState<string | null>(null);
  const [rejectDialog, setRejectDialog] = useState<string | null>(null);
  const [approveNotes, setApproveNotes] = useState('');
  const [rejectReason, setRejectReason] = useState('');
  const [actionLoading, setActionLoading] = useState(false);
  const [actionError, setActionError] = useState<string | null>(null);

  // Bulk action
  const [bulkAction, setBulkAction] = useState<'approve' | 'reject' | null>(null);
  const [bulkReason, setBulkReason] = useState('');

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

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

  const handleApprove = async () => {
    if (!approveDialog) return;
    setActionLoading(true);
    try {
      await adminApi.approveListing(approveDialog, approveNotes || undefined);
      setApproveDialog(null);
      setApproveNotes('');
      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.rejectListing(rejectDialog, rejectReason);
      setRejectDialog(null);
      setRejectReason('');
      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 handleBulkAction = async () => {
    if (!bulkAction || selected.size === 0) return;
    setActionLoading(true);
    try {
      await adminApi.bulkModerate(
        Array.from(selected),
        bulkAction,
        bulkReason || undefined,
      );
      setSelected(new Set());
      setBulkAction(null);
      setBulkReason('');
      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 toggleSelect = (id: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const toggleSelectAll = () => {
    if (!result) return;
    if (selected.size === result.data.length) {
      setSelected(new Set());
    } else {
      setSelected(new Set(result.data.map((item) => item.listingId)));
    }
  };

  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 flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-xl font-bold tracking-tight sm:text-2xl">Kiểm duyệt tin đăng</h1>
          <p className="text-sm text-muted-foreground">
            Duyệt hoặc từ chối các tin đăng chờ phê duyệt
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          {selected.size > 0 && (
            <>
              <Button
                size="sm"
                onClick={() => { setBulkAction('approve'); setBulkReason(''); }}
              >
                <CheckCircle className="mr-2 h-4 w-4" />
                Duyệt ({selected.size})
              </Button>
              <Button
                size="sm"
                variant="destructive"
                onClick={() => { setBulkAction('reject'); setBulkReason(''); }}
              >
                <XCircle className="mr-2 h-4 w-4" />
                Từ chối ({selected.size})
              </Button>
            </>
          )}
          <Button variant="outline" size="sm" onClick={fetchQueue}>
            <RefreshCw className="mr-2 h-4 w-4" />
            Làm mới
          </Button>
        </div>
      </div>

      <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">
              <CheckCircle className="h-8 w-8 text-green-500" />
              <p className="text-sm text-muted-foreground">
                Không có tin nào chờ kiểm duyệt
              </p>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-10">
                      <input
                        type="checkbox"
                        checked={selected.size === result.data.length && result.data.length > 0}
                        onChange={toggleSelectAll}
                        className="rounded border-input"
                        aria-label="Chọn tất cả tin đăng"
                      />
                    </TableHead>
                    <TableHead>Tiêu đề</TableHead>
                    <TableHead className="hidden sm:table-cell">Loại</TableHead>
                    <TableHead className="hidden md:table-cell">Giá</TableHead>
                    <TableHead className="hidden lg:table-cell">Người đăng</TableHead>
                    <TableHead>Điểm AI</TableHead>
                    <TableHead className="hidden md:table-cell">Ngày đăng</TableHead>
                    <TableHead className="text-right">Hành động</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {result.data.map((item) => (
                    <TableRow key={item.listingId}>
                      <TableCell>
                        <input
                          type="checkbox"
                          checked={selected.has(item.listingId)}
                          onChange={() => toggleSelect(item.listingId)}
                          className="rounded border-input"
                          aria-label={`Chọn tin: ${item.propertyTitle}`}
                        />
                      </TableCell>
                      <TableCell>
                        <div className="font-medium max-w-[200px] truncate">
                          {item.propertyTitle}
                        </div>
                        <div className="text-xs text-muted-foreground">
                          {item.transactionType === 'SALE' ? 'Bán' : 'Cho thuê'}
                        </div>
                      </TableCell>
                      <TableCell className="hidden sm:table-cell">
                        <Badge variant="outline">{item.propertyType}</Badge>
                      </TableCell>
                      <TableCell className="hidden md:table-cell">
                        {formatPrice(item.priceVND)} VND
                      </TableCell>
                      <TableCell className="hidden lg:table-cell">
                        <span className="text-sm">{item.sellerName}</span>
                      </TableCell>
                      <TableCell>
                        {moderationScoreBadge(item.moderationScore)}
                      </TableCell>
                      <TableCell className="hidden md:table-cell text-sm text-muted-foreground">
                        {new Date(item.createdAt).toLocaleDateString('vi-VN')}
                      </TableCell>
                      <TableCell>
                        <div className="flex justify-end gap-1">
                          <Button
                            variant="ghost"
                            size="icon"
                            title="Duyệt"
                            onClick={() => {
                              setApproveDialog(item.listingId);
                              setApproveNotes('');
                            }}
                          >
                            <CheckCircle className="h-4 w-4 text-green-600" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            title="Từ chối"
                            onClick={() => {
                              setRejectDialog(item.listingId);
                              setRejectReason('');
                            }}
                          >
                            <XCircle className="h-4 w-4 text-red-600" />
                          </Button>
                        </div>
                      </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} tin)
                  </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>

      {/* Approve dialog */}
      <Dialog open={!!approveDialog} onOpenChange={() => setApproveDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Duyệt tin đăng</DialogTitle>
            <DialogDescription>
              Tin đăng sẽ được hiển thị công khai sau khi duyệt.
            </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ý...' : 'Duyệt tin'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Reject dialog */}
      <Dialog open={!!rejectDialog} onOpenChange={() => setRejectDialog(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Từ chối tin đăng</DialogTitle>
            <DialogDescription>
              Vui lòng nhập lý do từ chối. Người đăng sẽ nhận được thông báo.
            </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'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Bulk action dialog */}
      <Dialog open={!!bulkAction} onOpenChange={() => setBulkAction(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {bulkAction === 'approve' ? 'Duyệt hàng loạt' : 'Từ chối hàng loạt'}
            </DialogTitle>
            <DialogDescription>
              <span className="flex items-center gap-2">
                <AlertTriangle className="h-4 w-4" />
                Thao tác sẽ áp dụng cho {selected.size} tin đăng đã chọn.
              </span>
            </DialogDescription>
          </DialogHeader>
          {bulkAction === 'reject' && (
            <Input
              placeholder="Lý do từ chối (bắt buộc)..."
              value={bulkReason}
              onChange={(e) => setBulkReason(e.target.value)}
            />
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setBulkAction(null)}>
              Hủy
            </Button>
            <Button
              variant={bulkAction === 'reject' ? 'destructive' : 'default'}
              onClick={handleBulkAction}
              disabled={actionLoading || (bulkAction === 'reject' && !bulkReason.trim())}
            >
              {actionLoading
                ? 'Đang xử lý...'
                : bulkAction === 'approve'
                  ? `Duyệt ${selected.size} tin`
                  : `Từ chối ${selected.size} tin`}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
