"use client";

import { useState } from "react";
import Link from "next/link";
import useSWR from "swr";
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  SortingState,
  useReactTable,
} from "@tanstack/react-table";
import { toast } from "sonner";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import AdminNewsService, { AdminComment } from "@/services/admin.news.service";
import {
  Search,
  Trash,
  Eye,
  CheckCircle,
  XCircle,
  MessageSquare,
  ChevronLeft,
  ChevronRight,
  RefreshCw,
  ExternalLink,
} from "lucide-react";

const statusLabels: Record<string, string> = {
  true: "Disetujui",
  false: "Pending",
};

const statusColors: Record<string, string> = {
  true: "bg-green-500",
  false: "bg-yellow-500",
};

const CommentsListPage = () => {
  const [sorting, setSorting] = useState<SortingState>([]);
  const [globalFilter, setGlobalFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("ALL");
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [commentToDelete, setCommentToDelete] = useState<AdminComment | null>(null);
  const [page, setPage] = useState(1);
  const [limit] = useState(10);

  const { data: commentsData, isLoading, mutate } = useSWR(
    `/admin/news/comments?page=${page}&limit=${limit}&status=${statusFilter}`,
    () => AdminNewsService.getAllComments({
      page,
      limit,
      isApproved: statusFilter === "ALL" ? undefined : statusFilter === "APPROVED",
    })
  );

  const handleApprove = async (id: string) => {
    try {
      await AdminNewsService.approveComment(id);
      toast.success("Komentar berhasil disetujui");
      mutate();
    } catch (error) {
      toast.error("Gagal menyetujui komentar");
    }
  };

  const handleReject = async (id: string) => {
    try {
      await AdminNewsService.rejectComment(id);
      toast.success("Komentar berhasil ditolak");
      mutate();
    } catch (error) {
      toast.error("Gagal menolak komentar");
    }
  };

  const handleDelete = async () => {
    if (!commentToDelete) return;

    try {
      await AdminNewsService.deleteComment(commentToDelete.id);
      toast.success("Komentar berhasil dihapus");
      mutate();
    } catch (error) {
      toast.error("Gagal menghapus komentar");
    } finally {
      setDeleteDialogOpen(false);
      setCommentToDelete(null);
    }
  };

  const comments = commentsData?.comments || [];

  const columns: ColumnDef<AdminComment>[] = [
    {
      accessorKey: "name",
      header: "Pengirim",
      cell: ({ row }) => (
        <div className="flex items-center gap-2">
          <Avatar className="h-8 w-8">
            <AvatarFallback className="text-xs bg-primary/10 text-primary">
              {row.original.name.charAt(0).toUpperCase()}
            </AvatarFallback>
          </Avatar>
          <div>
            <p className="font-medium">{row.original.name}</p>
            <p className="text-xs text-slate-500">{row.original.email}</p>
          </div>
        </div>
      ),
    },
    {
      accessorKey: "content",
      header: "Komentar",
      cell: ({ row }) => (
        <div>
          <p className="text-sm line-clamp-2">{row.original.content}</p>
          <Link
            href={`/berita/${row.original.news.slug}`}
            target="_blank"
            className="text-xs text-primary hover:underline flex items-center gap-1 mt-1"
          >
            {row.original.news.title}
            <ExternalLink className="h-3 w-3" />
          </Link>
        </div>
      ),
    },
    {
      accessorKey: "isApproved",
      header: "Status",
      cell: ({ row }) => (
        <Badge
          className={statusColors[String(row.original.isApproved)] || "bg-gray-500"}
        >
          {statusLabels[String(row.original.isApproved)] || "Unknown"}
        </Badge>
      ),
    },
    {
      accessorKey: "createdAt",
      header: "Tanggal",
      cell: ({ row }) => (
        <span className="text-sm text-slate-500">
          {new Date(row.original.createdAt).toLocaleDateString("id-ID", {
            day: "numeric",
            month: "short",
            year: "numeric",
          })}
        </span>
      ),
    },
    {
      id: "actions",
      header: "Aksi",
      cell: ({ row }) => (
        <div className="flex items-center gap-1">
          {!row.original.isApproved && (
            <Button
              variant="ghost"
              size="icon"
              className="text-green-600"
              onClick={() => handleApprove(row.original.id)}
              title="Setujui"
            >
              <CheckCircle className="h-4 w-4" />
            </Button>
          )}
          {row.original.isApproved && (
            <Button
              variant="ghost"
              size="icon"
              className="text-yellow-600"
              onClick={() => handleReject(row.original.id)}
              title="Tolak"
            >
              <XCircle className="h-4 w-4" />
            </Button>
          )}
          <Button
            variant="ghost"
            size="icon"
            className="text-red-600"
            onClick={() => {
              setCommentToDelete(row.original);
              setDeleteDialogOpen(true);
            }}
            title="Hapus"
          >
            <Trash className="h-4 w-4" />
          </Button>
        </div>
      ),
    },
  ];

  const table = useReactTable({
    data: comments,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    onSortingChange: setSorting,
    state: {
      sorting,
      globalFilter,
    },
    manualPagination: true,
    pageCount: commentsData?.pagination?.totalPages || 1,
  });

  const pendingCount = comments.filter((c) => !c.isApproved).length;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Moderasi Komentar</h1>
          <p className="text-slate-500">Kelola dan moderasi komentar pada berita</p>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-3 gap-4">
        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
          <p className="text-sm text-yellow-700">Pending</p>
          <p className="text-2xl font-bold text-yellow-800">
            {pendingCount}
          </p>
        </div>
        <div className="bg-green-50 border border-green-200 rounded-lg p-4">
          <p className="text-sm text-green-700">Disetujui</p>
          <p className="text-2xl font-bold text-green-800">
            {comments.filter((c) => c.isApproved).length}
          </p>
        </div>
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <p className="text-sm text-blue-700">Total</p>
          <p className="text-2xl font-bold text-blue-800">
            {commentsData?.pagination?.total || 0}
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="flex items-center gap-2">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500" />
          <Input
            placeholder="Cari komentar..."
            value={globalFilter}
            onChange={(e) => setGlobalFilter(e.target.value)}
            className="pl-9"
          />
        </div>

        <Select
          value={statusFilter}
          onValueChange={(value) => setStatusFilter(value || "ALL")}
        >
          <SelectTrigger className="w-40">
            <SelectValue placeholder="Filter status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="ALL">Semua</SelectItem>
            <SelectItem value="PENDING">Pending</SelectItem>
            <SelectItem value="APPROVED">Disetujui</SelectItem>
          </SelectContent>
        </Select>

        <Button
          variant="outline"
          size="icon"
          onClick={() => mutate()}
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </div>

      {/* Table */}
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <TableHead key={header.id}>
                    {header.isPlaceholder
                      ? null
                      : flexRender(header.column.columnDef.header, header.getContext())}
                  </TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {isLoading ? (
              <TableRow>
                <TableCell colSpan={columns.length} className="h-24 text-center">
                  Memuat data...
                </TableCell>
              </TableRow>
            ) : table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow key={row.id} data-state={row.getIsSelected() && "selected"}>
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id}>
                      {flexRender(cell.column.columnDef.cell, cell.getContext())}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={columns.length} className="h-24 text-center">
                  Tidak ada komentar.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-slate-500">
          Menampilkan {comments.length} dari {commentsData?.pagination?.total || 0} komentar
        </p>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page === 1}
          >
            <ChevronLeft className="h-4 w-4" />
          </Button>
          <span className="text-sm text-slate-500">
            Halaman {page} dari {commentsData?.pagination?.totalPages || 1}
          </span>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setPage((p) => p + 1)}
            disabled={page >= (commentsData?.pagination?.totalPages || 1)}
          >
            <ChevronRight className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Hapus Komentar</AlertDialogTitle>
            <AlertDialogDescription>
              Apakah Anda yakin ingin menghapus komentar dari &quot;{commentToDelete?.name}&quot;? 
              Tindakan ini tidak dapat dibatalkan.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Batal</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700">
              Hapus
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};

export default CommentsListPage;
