"use client";

import type { DashboardArticleCategory } from "@/components/dashboard/blogs/articles-types";
import { DataTableSkeleton } from "@/components/ui/data-table-skeleton";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Switch } from "@/components/ui/switch";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { toggleArticleCategoryStatus } from "@/lib/api/dashboard/article-categories-api";
import { cn } from "@/lib/utils";
import { ArrowDown, ArrowUp, Loader2, MoreVertical } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { toast } from "react-toastify";

interface CategoriesTableProps {
  data: DashboardArticleCategory[];
  isLoading?: boolean;
  error?: Error | null;
  onEdit: (item: DashboardArticleCategory) => void;
  onDelete: (item: DashboardArticleCategory) => void;
  onReorder: (items: { id: number; order: number }[]) => void;
  className?: string;
}

export function CategoriesTable({
  data,
  isLoading,
  error,
  onEdit,
  onDelete,
  onReorder,
  className,
}: CategoriesTableProps) {
  const t = useTranslations("dashboard.blogs.categories");
  const tCommon = useTranslations("common");
  const [pendingId, setPendingId] = useState<number | null>(null);

  const move = (index: number, direction: -1 | 1) => {
    const next = [...data];
    const target = index + direction;
    if (target < 0 || target >= next.length) return;
    [next[index], next[target]] = [next[target]!, next[index]!];
    onReorder(next.map((item, i) => ({ id: item.id, order: i + 1 })));
  };

  const toggleStatus = async (id: number) => {
    setPendingId(id);
    try { await toggleArticleCategoryStatus(id); } catch (e) { toast.error(e instanceof Error ? e.message : "Error"); } finally { setPendingId(null); }
  };

  if (isLoading) {
    return <DataTableSkeleton rows={8} columns={6} minWidth={900} />;
  }
  if (error) {
    return <div className="flex h-52 items-center justify-center text-sm text-destructive">{error.message}</div>;
  }
  if (!data.length) {
    return <div className="flex h-52 items-center justify-center text-sm text-muted-foreground">{tCommon("noResults")}</div>;
  }

  return (
    <div className={cn("w-full overflow-x-auto", className)}>
      <Table className="min-w-[900px] border-collapse bg-card">
        <TableHeader>
          <TableRow className="border-b border-border bg-highlights-bg hover:bg-highlights-bg">
            <TableHead className="h-12 w-14 px-4 text-center text-sm font-bold text-foreground">#</TableHead>
            <TableHead className="h-12 px-4 text-sm font-bold text-foreground">{t("headers.name")}</TableHead>
            <TableHead className="h-12 px-4 text-center text-sm font-bold text-foreground">{t("headers.parent")}</TableHead>
            <TableHead className="h-12 px-4 text-center text-sm font-bold text-foreground">{t("headers.count")}</TableHead>
            <TableHead className="h-12 px-4 text-center text-sm font-bold text-foreground">{t("headers.language")}</TableHead>
            <TableHead className="h-12 px-4 text-center text-sm font-bold text-foreground">{t("headers.slug")}</TableHead>
            <TableHead className="h-12 px-4 text-center text-sm font-bold text-foreground">{t("headers.settings")}</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {data.map((item, index) => {
            const isPending = pendingId === item.id;
            return (
            <TableRow
              key={item.id}
              aria-busy={isPending}
              className={cn(
                "h-[64px] border-b border-[#F4F4F4] bg-card transition-opacity hover:bg-card",
                isPending && "pointer-events-none opacity-60",
              )}
            >
              <TableCell className="px-4 text-center text-sm">{index + 1}</TableCell>
              <TableCell className="px-4 text-sm font-medium text-foreground">{item.name}</TableCell>
              <TableCell className="px-4 text-center text-sm text-foreground">{item.parent?.name ?? "—"}</TableCell>
              <TableCell className="px-4 text-center text-sm text-foreground">{item.articles_count ?? 0}</TableCell>
              <TableCell className="px-4 text-center text-sm text-foreground">{item.language ?? "—"}</TableCell>
              <TableCell className="px-4 text-center text-sm text-foreground">{item.slug ?? "—"}</TableCell>
              <TableCell className="px-4">
                <div className="flex items-center justify-center gap-2">
                  {/* <Button type="button" variant="ghost" size="icon" className="h-8 w-8" onClick={() => move(index, -1)} disabled={index === 0}>
                    <ArrowUp className="size-4" />
                  </Button>
                  <Button type="button" variant="ghost" size="icon" className="h-8 w-8" onClick={() => move(index, 1)} disabled={index === data.length - 1}>
                    <ArrowDown className="size-4" />
                  </Button> */}
                  {isPending ? (
                    <Loader2 className="size-4 animate-spin text-muted-foreground" aria-hidden />
                  ) : (
                    <Switch checked={item.is_active} onCheckedChange={() => toggleStatus(item.id)} />
                  )}
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button type="button" variant="outline" size="icon" className="h-10 w-10 rounded-xl border-border text-muted-foreground">
                        <MoreVertical className="size-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end" className="w-36">
                      <DropdownMenuItem onClick={() => onEdit(item)}>{tCommon("edit")}</DropdownMenuItem>
                      <DropdownMenuItem onClick={() => onDelete(item)} className="text-destructive">{tCommon("delete")}</DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              </TableCell>
            </TableRow>
          ); })}
        </TableBody>
      </Table>
    </div>
  );
}
