import React, { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  Card,
  CardHeader,
  CardTitle,
  CardContent,
} from "@/shared/common/ui/card";
import { Button } from "@/shared/common/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import {
  FileText,
  Plus,
  Edit,
  Trash2,
  Eye,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import { useLetterTemplates } from "@/user-management/hooks/useLetterTemplates";
import { LetterTemplateForm } from "./LetterTemplateForm";
import { LetterTemplate } from "@/user-management/services/api/letterTemplateService";
import { useLocalizedName } from "@/shared/common/localizedName";
import { toast } from "sonner";
import { Skeleton } from "@/shared/common/ui/skeleton";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { useTemplate } from "@/super-admin/components/templates/service/useTemplate";
import { headerFooterService } from "@/user-management/services/api/headerFooterService";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

interface Props {
  unitId: string;
}

const LetterTemplatesTable = ({ unitId }: Props) => {
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);

  // Pagination is server-side: skip/take are passed to the BE so we only
  // pull one page at a time instead of every template at once.
  const [pageIndex, setPageIndex] = useState(0);
  const [pageSize, setPageSize] = useState(10);

  const {
    letterTemplatesResponse,
    count: localCount,
    isLoading: isLocalLoading,
    isFetching: isLocalFetching,
    isError: isLocalError,
    refetch,
    createLetterTemplate,
    updateLetterTemplate,
    deleteLetterTemplate,
    isCreating,
    isUpdating,
    isDeleting,
  } = useLetterTemplates(unitId, {
    skip: pageIndex * pageSize,
    take: pageSize,
  });

  const totalPages = Math.max(1, Math.ceil(localCount / pageSize));

  const {
    templates: globalTemplatesResponse,
    isLoading: isGlobalLoading,
    adoptTemplate,
    isAdoptingTemplate,
  } = useTemplate();

  const { data: headersResponse } = useQuery({
    queryKey: ["headers", unitId],
    queryFn: () => headerFooterService.getHeadersByUnitId(unitId),
  });

  const { data: footersResponse } = useQuery({
    queryKey: ["footers", unitId],
    queryFn: () => headerFooterService.getFootersByUnitId(unitId),
  });

  const localizedName = useLocalizedName();

  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isAdoptDialogOpen, setIsAdoptDialogOpen] = useState(false);

  const [selectedTemplate, setSelectedTemplate] = useState<any | null>(null);
  const [selectedHeaderId, setSelectedHeaderId] = useState<string>("");
  const [selectedFooterId, setSelectedFooterId] = useState<string>("");

  const deleteTemplateName = selectedTemplate
    ? localizedName(selectedTemplate.name)
    : "";

  const isLoading = isLocalLoading || isGlobalLoading;
  const isError = isLocalError;

  const globalTemplates = Array.isArray(globalTemplatesResponse)
    ? globalTemplatesResponse
    : globalTemplatesResponse?.items || [];
  const localTemplates = letterTemplatesResponse?.items || [];

  const combinedTemplates = [
    ...globalTemplates.map((t: any) => ({ ...t, isGlobal: true })),
    ...localTemplates.map((t: any) => ({ ...t, isGlobal: false })),
  ];
  const preventDialogCloseFromTinyMce = (event: Event) => {
    const target = event.target as HTMLElement | null;

    if (
      target?.closest(
        ".tox-tinymce-aux, .moxman-window, .tam-assetmanager-root",
      )
    ) {
      event.preventDefault();
    }
  };

  const handleCreate = (values: any) => {
    createLetterTemplate(values, {
      onSuccess: (newTemplate) => {
        toast.success(
          `${localizedName(newTemplate.name)} ${t(
            "contentManagement.templateSuccessMsg",
          )}`,
        );
        refetch();
        setIsCreateDialogOpen(false);
      },
      onError: (error) => {
        handleError(error);
      },
    });
  };

  const handleUpdate = (values: any) => {
    if (!selectedTemplate) return;

    updateLetterTemplate(
      { id: selectedTemplate.id, data: values },
      {
        onSuccess: () => {
          toast.success(t("contentManagement.updateTemplate"));
          refetch();
          setIsEditDialogOpen(false);
          setSelectedTemplate(null);
        },
        onError: (error) => {
          handleError(error);
        },
      },
    );
  };

  const handleDelete = () => {
    if (!selectedTemplate) return;

    deleteLetterTemplate(
      { id: selectedTemplate.id },
      {
        onSuccess: () => {
          toast.success(t("contentManagement.deleteTemplate"));
          refetch();
          setIsDeleteDialogOpen(false);
          setSelectedTemplate(null);
        },
        onError: (error) => {
          handleError(error);
        },
      },
    );
  };

  const handleAdopt = () => {
    if (!selectedTemplate || !selectedHeaderId || !selectedFooterId) {
      toast.error(
        t(
          "contentManagement.pleaseSelectHeaderAndFooter",
          "Please select header and footer",
        ),
      );
      return;
    }

    adoptTemplate(
      {
        templateId: selectedTemplate.id,
        headerId: selectedHeaderId,
        footerId: selectedFooterId,
      },
      {
        onSuccess: () => {
          toast.success(
            t(
              "contentManagement.adoptSuccess",
              "Successfully adopted global template",
            ),
          );
          refetch();
          setIsAdoptDialogOpen(false);
          setSelectedTemplate(null);
          setSelectedHeaderId("");
          setSelectedFooterId("");
        },
        onError: (error) => {
          handleError(error);
        },
      },
    );
  };

  const openEditDialog = (template: any) => {
    setSelectedTemplate(template);
    setIsEditDialogOpen(true);
  };

  const openViewDialog = (template: any) => {
    setSelectedTemplate(template);
    setIsViewDialogOpen(true);
  };

  const openDeleteDialog = (template: any) => {
    setSelectedTemplate(template);
    setIsDeleteDialogOpen(true);
  };

  const openAdoptDialog = (template: any) => {
    setSelectedTemplate(template);
    setIsAdoptDialogOpen(true);
  };

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <FileText className="h-5 w-5 mr-2" />
            {t("contentManagement.letterTemplate")}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {Array(3)
              .fill(0)
              .map((_, index) => (
                <Skeleton key={index} className="h-12 w-full" />
              ))}
          </div>
        </CardContent>
      </Card>
    );
  }

  if (isError) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <FileText className="h-5 w-5 mr-2" />
            {t("contentManagement.letterTemplate")}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-sm text-red-600 dark:text-red-400">
            {t("contentManagement.failedToLoadTemplates")}
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <>
      <Card>
        <CardHeader>
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
              <CardTitle className="flex items-center">
                <FileText className="h-5 w-5 mr-2" />
                {t("contentManagement.letterTemplate")}
              </CardTitle>
              <p className="text-sm text-muted-foreground mt-1">
                {t("contentManagement.createMsg")}
              </p>
            </div>
            <Button
              onClick={() => setIsCreateDialogOpen(true)}
              size="sm"
              className="shrink-0"
            >
              <Plus className="h-4 w-4 mr-1" />
              {t("contentManagement.addTemplate")}
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {combinedTemplates.length === 0 ? (
            <div className="text-center py-8">
              <FileText className="mx-auto mb-4 h-12 w-12 text-gray-400 dark:text-gray-500" />
              <p className="text-gray-500 dark:text-gray-400">
                {t("contentManagement.noTemplates")}
              </p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="min-w-[150px]">
                      {t("common.name")}
                    </TableHead>
                    <TableHead className="min-w-[200px] hidden md:table-cell">
                      {t("contentManagement.sincerelyText")}
                    </TableHead>
                    <TableHead className="min-w-[120px] hidden sm:table-cell">
                      {t("common.createdDate")}
                    </TableHead>
                    <TableHead className="text-right min-w-[120px]">
                      {t("common.actions")}
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {combinedTemplates.map((template) => (
                    <TableRow
                      key={template.id}
                      className={
                        template.isGlobal
                          ? "bg-primary-50/50 hover:bg-primary-50 dark:bg-primary-950/30 dark:hover:bg-primary-900/40"
                          : ""
                      }
                    >
                      <TableCell className="font-medium">
                        <div className="flex flex-col">
                          <span className="flex items-center gap-2">
                            {localizedName(template.name)}
                            {template.isGlobal && (
                              <span className="rounded bg-primary-100 px-2 py-0.5 text-[10px] font-semibold text-primary-700 dark:bg-primary-900/50 dark:text-primary-200">
                                Global
                              </span>
                            )}
                          </span>
                          <span className="text-xs text-gray-500 dark:text-gray-400 md:hidden">
                            {template.sincerelyText &&
                            template.sincerelyText.length > 30
                              ? `${template.sincerelyText.substring(0, 30)}...`
                              : template.sincerelyText ||
                                t("common.notAvailable")}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell className="max-w-xs truncate hidden md:table-cell">
                        {template.sincerelyText || t("common.notAvailable")}
                      </TableCell>
                      <TableCell className="hidden sm:table-cell">
                        {template.createdAt
                          ? new Date(template.createdAt).toLocaleDateString()
                          : t("common.notAvailable")}
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex items-center justify-end gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => openViewDialog(template)}
                            title={t("contentManagement.viewTemplate")}
                          >
                            <Eye className="h-4 w-4" />
                          </Button>

                          {template.isGlobal ? (
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => openAdoptDialog(template)}
                              title={t(
                                "contentManagement.adoptTemplate",
                                "Adopt Template",
                              )}
                              className="h-8 border-primary-200 px-3 text-primary-700 hover:bg-primary-100 hover:text-primary-800 dark:border-primary-700/60 dark:text-primary-300 dark:hover:bg-primary-900/40 dark:hover:text-primary-200"
                            >
                              {t("common.adopt", "Adopt")}
                            </Button>
                          ) : (
                            <>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => openEditDialog(template)}
                                title={t("contentManagement.editTemplate")}
                              >
                                <Edit className="h-4 w-4" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => openDeleteDialog(template)}
                                className="text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300"
                                title={t("contentManagement.deleteTemplate")}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              {/* Pagination controls — apply to local templates only.
                  Globals are typically a small fixed list and are shown
                  in the same table on every page. */}
              <div className="mt-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div className="text-sm text-muted-foreground">
                  {t("common.page", "Page")} {pageIndex + 1} / {totalPages}
                  {localCount > 0 && (
                    <>
                      {" "}
                      • {localCount}{" "}
                      {t("contentManagement.letterTemplate", "templates")}
                    </>
                  )}
                </div>
                <div className="flex items-center gap-2">
                  <Select
                    value={String(pageSize)}
                    onValueChange={(v) => {
                      setPageSize(Number(v));
                      setPageIndex(0);
                    }}
                  >
                    <SelectTrigger className="h-8 w-[80px]">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {[10, 20, 50, 100].map((size) => (
                        <SelectItem key={size} value={String(size)}>
                          {size}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={pageIndex === 0 || isLocalFetching}
                    onClick={() => setPageIndex((p) => Math.max(0, p - 1))}
                  >
                    <ChevronLeft className="h-4 w-4" />
                    {t("common.previous", "Previous")}
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={pageIndex + 1 >= totalPages || isLocalFetching}
                    onClick={() => setPageIndex((p) => p + 1)}
                  >
                    {t("common.next", "Next")}
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Create Dialog */}
      <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
        <DialogContent
          className="max-h-[90vh] w-full max-w-[95vw] overflow-y-auto lg:max-w-[1200px] dark:border-gray-700 dark:bg-gray-900"
          onInteractOutside={preventDialogCloseFromTinyMce}
        >
          <DialogHeader>
            <DialogTitle>{t("contentManagement.createTemplate")}</DialogTitle>
          </DialogHeader>
          <LetterTemplateForm
            unitId={unitId}
            isSubmitting={isCreating}
            onCancel={() => setIsCreateDialogOpen(false)}
            onSubmitCreate={handleCreate}
          />
        </DialogContent>
      </Dialog>

      {/* Edit Dialog */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent
          className="max-h-[90vh] w-full max-w-[95vw] overflow-y-auto lg:max-w-[1200px] dark:border-gray-700 dark:bg-gray-900"
          onInteractOutside={preventDialogCloseFromTinyMce}
        >
          <DialogHeader>
            <DialogTitle>{t("contentManagement.editTemplate")}</DialogTitle>
          </DialogHeader>
          <LetterTemplateForm
            unitId={unitId}
            template={selectedTemplate}
            isSubmitting={isUpdating}
            onCancel={() => {
              setIsEditDialogOpen(false);
              setSelectedTemplate(null);
            }}
            onSubmitCreate={handleUpdate}
          />
        </DialogContent>
      </Dialog>

      {/* View Dialog */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-h-[90vh] w-full max-w-[95vw] overflow-y-auto lg:max-w-[1200px] dark:border-gray-700 dark:bg-gray-900">
          <DialogHeader>
            <DialogTitle>{t("contentManagement.viewTemplate")}</DialogTitle>
          </DialogHeader>
          {selectedTemplate && (
            <div className="space-y-4">
              <div>
                <label className="text-sm font-medium text-gray-600 dark:text-gray-300">
                  {t("common.name")}
                </label>
                <p className="mt-1 text-sm text-gray-900 dark:text-gray-100">
                  {localizedName(selectedTemplate.name)}
                </p>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-600 dark:text-gray-300">
                  {t("contentManagement.sincerelyText")}
                </label>
                <p className="mt-1 text-sm text-gray-900 dark:text-gray-100">
                  {selectedTemplate.sincerelyText || t("common.notAvailable")}
                </p>
              </div>
              <div>
                <label className="text-sm font-medium text-gray-600 dark:text-gray-300">
                  {t("contentManagement.body")}
                </label>
                <div
                  className="mt-1 max-h-60 overflow-y-auto rounded-md border bg-gray-50 p-3 text-sm text-gray-900 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-100"
                  dangerouslySetInnerHTML={{ __html: selectedTemplate.body }}
                />
              </div>
              <div className="flex justify-end">
                <Button onClick={() => setIsViewDialogOpen(false)}>
                  {t("common.close")}
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Adopt Dialog */}
      <Dialog open={isAdoptDialogOpen} onOpenChange={setIsAdoptDialogOpen}>
        <DialogContent className="max-w-md dark:border-gray-700 dark:bg-gray-900">
          <DialogHeader>
            <DialogTitle>
              {t("contentManagement.adoptTemplate", "Adopt Template")}
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div>
              <label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
                {t("contentManagement.selectHeader", "Select Header")}
              </label>
              <Select
                value={selectedHeaderId}
                onValueChange={setSelectedHeaderId}
              >
                <SelectTrigger>
                  <SelectValue
                    placeholder={t(
                      "contentManagement.selectHeader",
                      "Select Header",
                    )}
                  />
                </SelectTrigger>
                <SelectContent>
                  {headersResponse?.data?.items?.map((header: any) => (
                    <SelectItem key={header.id} value={header.id}>
                      {localizedName(header.name)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300">
                {t("contentManagement.selectFooter", "Select Footer")}
              </label>
              <Select
                value={selectedFooterId}
                onValueChange={setSelectedFooterId}
              >
                <SelectTrigger>
                  <SelectValue
                    placeholder={t(
                      "contentManagement.selectFooter",
                      "Select Footer",
                    )}
                  />
                </SelectTrigger>
                <SelectContent>
                  {footersResponse?.data?.items?.map((footer: any) => (
                    <SelectItem key={footer.id} value={footer.id}>
                      {localizedName(footer.name)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="flex justify-end gap-2">
            <Button
              variant="outline"
              onClick={() => setIsAdoptDialogOpen(false)}
            >
              {t("common.cancel")}
            </Button>
            <Button
              onClick={handleAdopt}
              disabled={
                isAdoptingTemplate || !selectedHeaderId || !selectedFooterId
              }
            >
              {isAdoptingTemplate
                ? t("common.adopting", "Adopting...")
                : t("common.adopt", "Adopt")}
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t("contentManagement.deleteTemplate")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t("contentManagement.deleteTemplateConfirm", {
                name: deleteTemplateName,
              })
                // Fallback if resources still use the legacy `{name}` placeholder.
                .replace("{{name}}", deleteTemplateName)
                .replace("{name}", deleteTemplateName)}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={isDeleting}
              className="bg-red-600 hover:bg-red-700"
            >
              {isDeleting ? t("common.deleting") : t("common.delete")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default LetterTemplatesTable;
