// components/tag-based-reference-numbers.tsx
"use client";

import * as React from "react";
import { Plus, Trash2, Loader2, AlertCircle, X } from "lucide-react";
import { useTranslation } from "react-i18next";

import { useRecordTagPrefixes } from "@/user-management/hooks/useRecordTagPrefixes";
import { useRecordTags } from "@/user-management/hooks/useRecordTags";
import { Label } from "@/shared/common/ui/label";
import { useQueryClient } from "@tanstack/react-query";
import { prefixSuffixService } from "@/user-management/services/api/prefixSuffixService";
import { cn } from "@/shared/lib/utils";
import { RecordTagSelector } from "./RecordTagSelector";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/shared/common/ui/dialog";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Badge } from "@/shared/common/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import { Skeleton } from "@/shared/common/ui/skeleton";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/shared/common/ui/pagination";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { useLocalizedName } from "@/shared/common/localizedName";
import { CreatePrefixPayload } from "@/user-management/services/api/prefixSuffixService";

// ─── Types ─────────────────────────────────────────────

export interface TagBasedReferenceNumbersProps {
  unitId: string;
  className?: string;
}

export interface PrefixItem {
  id: string;
  prefix: string;
  suffix?: string;
  description?: string;
  createdAt: string;
  updatedAt: string;
}

// ─── Component ─────────────────────────────────────────

export function TagBasedReferenceNumbers({
  unitId,
  className,
}: TagBasedReferenceNumbersProps) {
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const queryClient = useQueryClient();
  const [selectedTagId, setSelectedTagId] = React.useState<string>("");
  const [isAddDialogOpen, setIsAddDialogOpen] = React.useState(false);
  const [deleteTargetId, setDeleteTargetId] = React.useState<string | null>(
    null,
  );
  const [countPopup, setCountPopup] = React.useState<{
    itemId: string | null;
    currentCount: number;
  } | null>(null);
  const [countValue, setCountValue] = React.useState("");
  const [currentPage, setCurrentPage] = React.useState(1);
  const pageSize = 10;

  const skip = (currentPage - 1) * pageSize;

  const { recordTagsList, isLoadingRecordTagsList } = useRecordTags({ unitId });

  const {
    prefixes,
    total,
    isLoadingPrefixes,
    isErrorPrefixes,
    createPrefix,
    isCreatingPrefix,
    deletePrefix,
    isDeletingPrefix,
  } = useRecordTagPrefixes({
    unitId,
    recordTagId: selectedTagId || undefined,
    skip,
    take: pageSize,
  });

  const totalPages = Math.ceil(total / pageSize);

  // Reset page when tag changes
  React.useEffect(() => {
    setCurrentPage(1);
  }, [selectedTagId]);

  // Get selected tag details for display
  const selectedTag = React.useMemo(() => {
    return recordTagsList?.items?.find((tag) => tag.id === selectedTagId);
  }, [recordTagsList, selectedTagId]);

  // Handle add prefix
  const handleAddPrefix = React.useCallback(
    (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      const formData = new FormData(e.currentTarget);
      const nameAm = (formData.get("nameAm") as string)?.trim();
      const nameEn = (formData.get("nameEn") as string)?.trim();

      if (!nameAm || !nameEn) return;

      const payload: CreatePrefixPayload = {
        name: { am: nameAm, en: nameEn },
        unitId,
        isForCC: false,
        recordTagId: selectedTagId || undefined,
      };

      createPrefix(payload, {
        onSuccess: () => {
          setIsAddDialogOpen(false);
        },
      });
    },
    [createPrefix, selectedTagId, unitId],
  );

  // Handle delete
  const handleDelete = React.useCallback(() => {
    if (deleteTargetId) {
      deletePrefix(deleteTargetId, {
        onSuccess: () => setDeleteTargetId(null),
      });
    }
  }, [deletePrefix, deleteTargetId]);

  const getCount = (item: any): number =>
    item.recordSequences?.[0]?.count ?? item.count ?? 0;

  const getSequenceId = (item: any): string | null =>
    item.recordSequences?.[0]?.id ?? item.sequenceId ?? null;

  const openCountPopup = (item: any) => {
    console.log("[TagBasedRef] prefix item:", item);
    const currentCount = getCount(item);
    const sequenceId = getSequenceId(item);
    setCountPopup({ itemId: sequenceId, currentCount });
    setCountValue(String(currentCount));
  };

  const closeCountPopup = () => {
    setCountPopup(null);
    setCountValue("");
    queryClient.invalidateQueries({ queryKey: ["recordTagPrefixes", unitId, selectedTagId] });
  };

  const handleCountSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!countPopup || !countPopup.itemId) return;
    const newCount = parseInt(countValue, 10);
    if (isNaN(newCount) || newCount < 0) return;
    prefixSuffixService.updateCount(countPopup.itemId, newCount).then(() => {
      closeCountPopup();
    });
  };

  return (
    <div className={cn("space-y-6", className)}>
      {/* ─── Header Section: Tag Selector + Add Button ─── */}
      <div className="flex flex-col sm:flex-row items-start sm:items-end gap-4">
        <div className="flex-1 w-full sm:w-auto space-y-2">
          <Label className="text-sm font-medium">
            {t("nav.selectTag") || "Select Record Tag"}
          </Label>
          <RecordTagSelector
            unitId={unitId}
            selectedTagIds={selectedTagId ? [selectedTagId] : []}
            onChange={(ids) => setSelectedTagId(ids[0] || "")}
            placeholder={
              t("nav.selectTag") || "Choose a tag to view prefixes..."
            }
            multiple={false}
            disabled={isLoadingRecordTagsList}
          />
        </div>

        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogTrigger asChild>
            <Button
              className="shrink-0"
              disabled={!selectedTagId || isLoadingPrefixes}
            >
              <Plus className="h-4 w-4 mr-2" />
              {t("contentManagement.addPrefix") || "Add Prefix"}
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>
                {t("contentManagement.addPrefix") || "Add New Prefix"}
              </DialogTitle>
            </DialogHeader>

            <form
              id="add-prefix-form"
              onSubmit={handleAddPrefix}
              className="space-y-4"
            >
              <div className="space-y-2">
                <Label htmlFor="nameAm" className="dark:text-gray-200">
                  {t("contentManagement.amharicName")} *
                </Label>
                <Input
                  id="nameAm"
                  name="nameAm"
                  placeholder={t("contentManagement.amharicName")}
                  required
                  autoFocus
                  className="dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="nameEn" className="dark:text-gray-200">
                  {t("contentManagement.englishName")} *
                </Label>
                <Input
                  id="nameEn"
                  name="nameEn"
                  placeholder={t("contentManagement.englishName")}
                  required
                  className="dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                />
              </div>
            </form>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setIsAddDialogOpen(false)}
              >
                {t("common.cancel") || "Cancel"}
              </Button>
              <Button
                type="submit"
                form="add-prefix-form"
                disabled={isCreatingPrefix}
              >
                {isCreatingPrefix && (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                )}
                {t("common.save") || "Save"}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* ─── Selected Tag Info ─── */}
      {selectedTag && (
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <span>Showing prefixes for:</span>
          <Badge variant="outline">{localizedName(selectedTag.name)}</Badge>
          <span className="text-xs">({total} items)</span>
        </div>
      )}

      {/* ─── Table Section ─── */}
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[80px]">
                {t("common.no") || "#"}
              </TableHead>
              <TableHead>{t("contentManagement.amharicName")}</TableHead>
              <TableHead>{t("contentManagement.englishName")}</TableHead>
              <TableHead>
                {t("contentManagement.createdAt") || "Created"}
              </TableHead>
              <TableHead className="w-[100px]">
                {t("contentManagement.count") || "Count"}
              </TableHead>
              <TableHead className="w-[100px] text-right">
                {t("common.actions") || "Actions"}
              </TableHead>
            </TableRow>
          </TableHeader>

          <TableBody>
            {/* Loading State */}
            {isLoadingPrefixes && (
              <>
                {Array.from({ length: 5 }).map((_, i) => (
                  <TableRow key={`skeleton-${i}`}>
                    <TableCell>
                      <Skeleton className="h-4 w-8" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-24" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-20" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-32" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-24" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-8 w-8 ml-auto" />
                    </TableCell>
                  </TableRow>
                ))}
              </>
            )}

            {/* Error State */}
            {isErrorPrefixes && !isLoadingPrefixes && (
              <TableRow>
                <TableCell colSpan={6} className="h-32 text-center">
                  <div className="flex flex-col items-center gap-2 text-destructive">
                    <AlertCircle className="h-8 w-8" />
                    <p className="text-sm">
                      {t("common.errorLoading") || "Failed to load prefixes"}
                    </p>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => window.location.reload()}
                    >
                      {t("common.retry") || "Retry"}
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            )}

            {/* Empty States */}
            {!isLoadingPrefixes && !isErrorPrefixes && (
              <>
                {!selectedTagId && (
                  <TableRow>
                    <TableCell colSpan={6} className="h-32 text-center">
                      <div className="flex flex-col items-center gap-2 text-muted-foreground">
                        <span className="text-2xl">🏷️</span>
                        <p className="text-sm">
                          {t("nav.selectTag") ||
                            "Select a tag above to view its prefixes"}
                        </p>
                      </div>
                    </TableCell>
                  </TableRow>
                )}

                {selectedTagId && prefixes.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={6} className="h-32 text-center">
                      <div className="flex flex-col items-center gap-2 text-muted-foreground">
                        <Plus className="h-8 w-8 opacity-50" />
                        <p className="text-sm">
                          {t("nav.emptyState") ||
                            "No prefixes found for this tag"}
                        </p>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setIsAddDialogOpen(true)}
                        >
                          {t("nav.addNew") || "Add your first prefix"}
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                )}

                {/* Data Rows */}
                {prefixes.map((prefix, index: number) => {
                  const count = getCount(prefix);
                  return (
                    <TableRow key={prefix.id} className="group">
                      <TableCell className="text-muted-foreground text-sm">
                        {skip + index + 1}
                      </TableCell>
                      <TableCell className="font-medium">
                        {prefix.name?.am || (
                          <span className="text-muted-foreground text-sm">—</span>
                        )}
                      </TableCell>
                      <TableCell>
                        {prefix.name?.en || (
                          <span className="text-muted-foreground text-sm">—</span>
                        )}
                      </TableCell>
                      <TableCell className="text-muted-foreground text-sm">
                        {new Date(prefix.createdAt).toLocaleDateString()}
                      </TableCell>
                      <TableCell>
                        <button
                          onClick={() => openCountPopup(prefix)}
                          className="text-primary-600 hover:text-primary-800 dark:text-primary-400 dark:hover:text-primary-300 underline cursor-pointer text-sm"
                        >
                          {count}
                        </button>
                      </TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors"
                          onClick={() => setDeleteTargetId(prefix.id)}
                          disabled={isDeletingPrefix}
                          title="Delete this prefix"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </>
            )}
          </TableBody>
        </Table>
      </div>

      {/* ─── Pagination ─── */}
      {totalPages > 1 && (
        <Pagination>
          <PaginationContent>
            <PaginationItem>
              <PaginationPrevious
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                className={cn(
                  currentPage === 1 && "pointer-events-none opacity-50",
                )}
              />
            </PaginationItem>

            {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
              <PaginationItem key={page}>
                <PaginationLink
                  isActive={currentPage === page}
                  onClick={() => setCurrentPage(page)}
                >
                  {page}
                </PaginationLink>
              </PaginationItem>
            ))}

            <PaginationItem>
              <PaginationNext
                onClick={() =>
                  setCurrentPage((p) => Math.min(totalPages, p + 1))
                }
                className={cn(
                  currentPage === totalPages &&
                    "pointer-events-none opacity-50",
                )}
              />
            </PaginationItem>
          </PaginationContent>
        </Pagination>
      )}

      {/* ─── Count Update Popup ─── */}
      {countPopup && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6 w-80">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-semibold dark:text-white">
                {t("contentManagement.updateCount")}
              </h3>
              <button
                onClick={closeCountPopup}
                className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
              >
                <X className="h-5 w-5" />
              </button>
            </div>
            <form onSubmit={handleCountSubmit}>
              <div className="space-y-2 mb-4">
                <Label htmlFor="countValue" className="dark:text-gray-200">
                  {t("contentManagement.value")} *
                </Label>
                <Input
                  id="countValue"
                  type="number"
                  min="0"
                  value={countValue}
                  onChange={(e) => setCountValue(e.target.value)}
                  placeholder={t("contentManagement.enterValue")}
                  className="dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                />
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  {t("contentManagement.currentCount")}: {countPopup.currentCount}
                </p>
                {!countPopup.itemId && (
                  <p className="text-xs text-red-500">
                    No sequence found for this prefix. Use it in a record first.
                  </p>
                )}
              </div>
              <div className="flex gap-2 justify-end">
                <Button type="button" variant="outline" onClick={closeCountPopup}>
                  {t("common.cancel")}
                </Button>
                <Button type="submit" disabled={!countPopup.itemId}>
                  {t("common.submit")}
                </Button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ─── Delete Confirmation ─── */}
      <AlertDialog
        open={!!deleteTargetId}
        onOpenChange={(open) => !open && setDeleteTargetId(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t("prefixes.deleteConfirmTitle") || "Delete Tag-Based Reference Prefix?"}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t("prefixes.deleteConfirmDescription") ||
                "Are you sure you want to delete this prefix? This action cannot be undone and will permanently remove this prefix from the system."}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeletingPrefix}>
              {t("common.cancel") || "Cancel"}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={isDeletingPrefix}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {isDeletingPrefix && (
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              )}
              {t("common.delete") || "Delete"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
