'use client';

import {
  CheckCircle,
  XCircle,
  RefreshCw,
  ChevronLeft,
  ChevronRight,
  AlertTriangle,
  X,
  Flag,
} from 'lucide-react';
import { useEffect, useState, useCallback } from 'react';
import { Signal } from '@/components/design-system/signal';
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 ModerationQueueItem, type PaginatedResult } from '@/lib/admin-api';

type QueueTab = 'pending' | 'flagged' | 'approved' | 'rejected';

const TABS: { id: QueueTab; label: string; endpoint?: string }[] = [
  { id: 'pending', label: 'Chờ duyệt' },
  { id: 'flagged', label: 'Bị gắn cờ' },
  { id: 'approved', label: 'Đã duyệt' },
  { id: 'rejected', label: 'Đã từ chối' },
];

function AiScorePill({ score }: { score: number | null }) {
  if (score === null) return <span className="font-mono text-xs text-foreground-dim">N/A</span>;
  const dir = score >= 80 ? 'up' : score >= 50 ? 'neutral' : 'down';
  return <Signal direction={dir} label={String(score)} />;
}

function ModerationStatusChip({ tab }: { tab: QueueTab }) {
  if (tab === 'approved') return <StatusChip status="active" hideDot />;
  if (tab === 'rejected') return <StatusChip status="rejected" hideDot />;
  if (tab === 'flagged') return <StatusChip status="pending" hideDot />;
  return <StatusChip status="pending" hideDot />;
}

export default function AdminModerationPage() {
  const [activeTab, setActiveTab] = useState<QueueTab>('pending');
  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);

  const [selected, setSelected] = useState<Set<string>>(new Set());

  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);

  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(() => {
    setSelected(new Set());
    setPage(1);
  }, [activeTab]);

  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)));
    }
  };

  const isActionable = activeTab === 'pending' || activeTab === 'flagged';

  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>
      )}

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

      {/* Tabs */}
      <div className="flex gap-0 border-b border-border">
        {TABS.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`relative px-4 py-2 text-sm font-medium transition-colors ${
              activeTab === tab.id
                ? 'text-foreground after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-primary'
                : 'text-foreground-muted hover:text-foreground'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* 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">
              <CheckCircle className="h-8 w-8 text-signal-up" />
              <p className="text-sm text-foreground-muted">Không có tin nào trong hàng đợi này</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">
                    {isActionable && (
                      <TableHead className="w-9 px-3">
                        <input
                          type="checkbox"
                          checked={selected.size === result.data.length && result.data.length > 0}
                          onChange={toggleSelectAll}
                          className="rounded border-border"
                          aria-label="Chọn tất cả tin đăng"
                        />
                      </TableHead>
                    )}
                    <TableHead className="text-heading-xs uppercase text-foreground-muted">Tiêu đề</TableHead>
                    <TableHead className="hidden sm:table-cell text-heading-xs uppercase text-foreground-muted">Loại</TableHead>
                    <TableHead className="hidden md:table-cell text-heading-xs uppercase text-foreground-muted text-right">Giá (VND)</TableHead>
                    <TableHead className="hidden lg:table-cell text-heading-xs uppercase text-foreground-muted">Người đăng</TableHead>
                    <TableHead className="text-heading-xs uppercase text-foreground-muted text-center">Điểm AI</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 đăng</TableHead>
                    {isActionable && <TableHead className="text-right text-heading-xs uppercase text-foreground-muted">Hành động</TableHead>}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {result.data.map((item) => (
                    <TableRow
                      key={item.listingId}
                      className="h-row-compact border-b border-border hover:bg-background-surface transition-colors"
                    >
                      {isActionable && (
                        <TableCell className="px-3">
                          <input
                            type="checkbox"
                            checked={selected.has(item.listingId)}
                            onChange={() => toggleSelect(item.listingId)}
                            className="rounded border-border"
                            aria-label={`Chọn tin: ${item.propertyTitle}`}
                          />
                        </TableCell>
                      )}
                      <TableCell>
                        <div className="font-medium max-w-[200px] truncate text-sm">{item.propertyTitle}</div>
                        <div className="text-xs text-foreground-dim">
                          {item.transactionType === 'SALE' ? 'Bán' : 'Cho thuê'}
                        </div>
                      </TableCell>
                      <TableCell className="hidden sm:table-cell">
                        <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.propertyType}
                        </span>
                      </TableCell>
                      <TableCell className="hidden md:table-cell font-mono text-data-sm tabular-nums text-right">
                        {new Intl.NumberFormat('vi-VN').format(item.priceVND)}
                      </TableCell>
                      <TableCell className="hidden lg:table-cell text-sm text-foreground-muted">
                        {item.sellerName}
                      </TableCell>
                      <TableCell className="text-center">
                        <AiScorePill score={item.moderationScore} />
                      </TableCell>
                      <TableCell>
                        <ModerationStatusChip tab={activeTab} />
                      </TableCell>
                      <TableCell className="hidden md:table-cell font-mono text-data-sm text-foreground-dim">
                        {new Date(item.createdAt).toLocaleDateString('vi-VN')}
                      </TableCell>
                      {isActionable && (
                        <TableCell>
                          <div className="flex justify-end gap-1">
                            <button
                              title="Duyệt"
                              onClick={() => { setApproveDialog(item.listingId); setApproveNotes(''); }}
                              className="rounded p-1 text-signal-up hover:bg-signal-up/10 transition-colors"
                              aria-label={`Duyệt tin: ${item.propertyTitle}`}
                            >
                              <CheckCircle className="h-4 w-4" />
                            </button>
                            <button
                              title="Từ chối"
                              onClick={() => { setRejectDialog(item.listingId); setRejectReason(''); }}
                              className="rounded p-1 text-signal-down hover:bg-signal-down/10 transition-colors"
                              aria-label={`Từ chối tin: ${item.propertyTitle}`}
                            >
                              <XCircle className="h-4 w-4" />
                            </button>
                            <button
                              title="Gắn cờ"
                              className="rounded p-1 text-signal-neutral hover:bg-signal-neutral/10 transition-colors"
                              aria-label={`Gắn cờ tin: ${item.propertyTitle}`}
                            >
                              <Flag className="h-4 w-4" />
                            </button>
                          </div>
                        </TableCell>
                      )}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              {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} 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>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Bulk action bar (sticky bottom) */}
      {isActionable && selected.size > 0 && (
        <div className="sticky bottom-4 z-dropdown flex items-center justify-between rounded-lg border border-border-strong bg-background-elevated px-4 py-2.5 shadow-elevation-2">
          <span className="text-sm font-medium">
            Đã chọn <span className="font-mono tabular-nums">{selected.size}</span> tin
          </span>
          <div className="flex gap-2">
            <Button size="sm" onClick={() => { setBulkAction('approve'); setBulkReason(''); }}>
              <CheckCircle className="mr-1.5 h-3.5 w-3.5" />
              Duyệt tất cả
            </Button>
            <Button size="sm" variant="destructive" onClick={() => { setBulkAction('reject'); setBulkReason(''); }}>
              <XCircle className="mr-1.5 h-3.5 w-3.5" />
              Từ chối tất cả
            </Button>
            <Button size="sm" variant="outline" onClick={() => setSelected(new Set())}>
              Bỏ chọn
            </Button>
          </div>
        </div>
      )}

      {/* 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>
  );
}
