"use client";

import type { DashboardArticleTag } 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 { toggleArticleTagStatus } from "@/lib/api/dashboard/article-tags-api";
import { cn } from "@/lib/utils";
import { Loader2, MoreVertical } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { toast } from "react-toastify";

interface TagsTableProps {
  data: DashboardArticleTag[];
  isLoading?: boolean;
  error?: Error | null;
  onEdit: (item: DashboardArticleTag) => void;
  onDelete: (item: DashboardArticleTag) => void;
  className?: string;
}

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

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

  if (isLoading) {
    return <DataTableSkeleton rows={8} columns={4} minWidth={800} />;
  }
  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-[800px] 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.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.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">
                  {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>
  );
}
