"use client";

import type { DashboardArticleItem } 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 { StatusBadge } from "@/components/ui/status-badge";
import { Switch } from "@/components/ui/switch";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Link } from "@/i18n/routing";
import { getAssetUrl } from "@/lib/api-enabled";
import { cn } from "@/lib/utils";
import { Calendar, Loader2, MoreVertical } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import Image from "next/image";

interface BlogsTableProps {
  data: DashboardArticleItem[];
  page: number;
  perPage: number;
  isLoading?: boolean;
  error?: Error | null;
  pendingBlogId?: number | null;
  onToggleFeatured?: (id: number, value: boolean) => void;
  onDelete?: (item: DashboardArticleItem) => void;
  onChangeStatus?: (item: DashboardArticleItem) => void;
  className?: string;
}

export function BlogsTable({
  data,
  page,
  perPage,
  isLoading,
  error,
  pendingBlogId,
  onToggleFeatured,
  onDelete,
  onChangeStatus,
  className,
}: BlogsTableProps) {
  const t = useTranslations("dashboard.blogs.table");
  const tCommon = useTranslations("common");
  const locale = useLocale();

  const formatDate = (value?: string | null) => {
    if (!value) return t("unpublished");
    return new Intl.DateTimeFormat(locale === "ar" ? "ar-SA" : "en-US", {
      day: "numeric",
      month: "long",
      year: "numeric",
    }).format(new Date(value));
  };

  if (isLoading) {
    return <DataTableSkeleton rows={perPage ?? 8} columns={7} minWidth={1040} />;
  }
  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-[1020px] 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 w-[360px] px-4 text-sm font-bold text-foreground">
              {t("headers.title")}
            </TableHead>
            <TableHead className="h-12 w-[170px] px-4 text-center text-sm font-bold text-foreground">
              {t("headers.category")}
            </TableHead>
            <TableHead className="h-12 w-[150px] px-4 text-center text-sm font-bold text-foreground">
              {t("headers.status")}
            </TableHead>
            <TableHead className="h-12 w-[170px] px-4 text-center text-sm font-bold text-foreground">
              {t("headers.publishDate")}
            </TableHead>
            <TableHead className="h-12 w-[110px] px-4 text-center text-sm font-bold text-foreground">
              {t("headers.featured")}
            </TableHead>
            <TableHead className="h-12 w-[100px] px-4 text-center text-sm font-bold text-foreground">
              {t("headers.settings")}
            </TableHead>
          </TableRow>
        </TableHeader>

        <TableBody>
          {data.map((item, index) => {
            const rowIndex = (page - 1) * perPage + index + 1;
            const imageSrc = getAssetUrl(item.featured_image || item.image || "");
            const categoryName = item.category?.name ?? "—";
            const isPending = pendingBlogId === item.id;

            return (
              <TableRow
                key={item.id}
                aria-busy={isPending}
                className={cn(
                  "h-[72px] 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">{rowIndex}</TableCell>

                <TableCell className="px-4">
                  <div className="flex items-center gap-3">
                    {imageSrc ? (
                      <Image
                        src={imageSrc}
                        alt={item.image_alt ?? item.title}
                        width={48}
                        height={44}
                        className="h-11 w-12 rounded-md object-cover"
                      />
                    ) : (
                      <div className="h-11 w-12 rounded-md bg-muted" />
                    )}
                    <div className="max-w-[260px]">
                      <p className="line-clamp-2 text-sm font-medium text-foreground">
                        {item.title}
                      </p>
                    </div>
                  </div>
                </TableCell>

                <TableCell className="px-4 text-center text-sm text-foreground">
                  {categoryName}
                </TableCell>

                <TableCell className="px-4 text-center">
                  <StatusBadge status={item.status} className="h-7 min-w-[72px]" />
                </TableCell>

                <TableCell className="px-4 text-center">
                  <div className="flex items-center justify-center gap-2 text-sm text-foreground">
                    <span>{formatDate(item.published_at ?? item.scheduled_at)}</span>
                    <Calendar className="size-4 text-muted-foreground" />
                  </div>
                </TableCell>

                <TableCell className="px-4 text-center">
                  <div className="flex justify-center">
                    {isPending ? (
                      <Loader2 className="size-4 animate-spin text-muted-foreground" aria-hidden />
                    ) : (
                      <Switch
                        checked={item.is_featured}
                        onCheckedChange={(checked) => onToggleFeatured?.(item.id, checked)}
                      />
                    )}
                  </div>
                </TableCell>

                <TableCell className="px-4 text-center">
                  <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-44">
                      <DropdownMenuItem asChild>
                        <Link href={`/dashboard/blogs/${item.id}`}>{t("actions.preview")}</Link>
                      </DropdownMenuItem>
                      <DropdownMenuItem asChild>
                        <Link href={`/dashboard/blogs/${item.id}/edit`}>{t("actions.edit")}</Link>
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => onChangeStatus?.(item)}>
                        {t("actions.changeStatus")}
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => onDelete?.(item)}
                        className="text-destructive"
                      >
                        {t("actions.delete")}
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </div>
  );
}
