import React, { useState } from "react";
import { sanitizeHtml } from "@/shared/lib/sanitize";
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 { FileText, Plus, Edit, Trash2, Eye } from "lucide-react";
import { TemplateForm } from "./TemplateForm";
import { CreateTemplateTypes } from "../types/templateTypes";
import { useLocalizedName } from "@/shared/common/localizedName";
import { toast } from "sonner";
import { t } from "i18next";
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 "../service/useTemplate";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

const TemplateTable = () => {
  const { handleError } = useErrorHandler(t);
  const {
    templates,
    isLoading,
    isError,
    refetch,
    createTemplate,
    updateTemplate,
    deleteTemplate,
    isCreatingTemplate,
    isUpdatingTemplate,
    isDeletingTemplate,
  } = useTemplate();

  const templateList: CreateTemplateTypes[] = Array.isArray(templates) ? templates : templates?.items || [];

  const localizedName = useLocalizedName();

  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isViewDialogOpen, setIsViewDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [selectedTemplate, setSelectedTemplate] =
    useState<CreateTemplateTypes | null>(null);

  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: CreateTemplateTypes) => {
    createTemplate(values, {
      onSuccess: (newTemplate: any) => {
        // Assume API returns the created config or just general success
        toast.success(t("contentManagement.templateSuccessMsg"));
        refetch();
        setIsCreateDialogOpen(false);
      },
      onError: (error) => {
        handleError(error);
      },
    });
  };

  const handleUpdate = (values: CreateTemplateTypes) => {
    if (!selectedTemplate?.id) return;

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

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

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

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

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

  const openDeleteDialog = (template: CreateTemplateTypes) => {
    setSelectedTemplate(template);
    setIsDeleteDialogOpen(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">
            {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>
          {templateList.length === 0 ? (
            <div className="text-center py-8">
              <FileText className="h-12 w-12 text-gray-400 dark:text-gray-500 mx-auto mb-4" />
              <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="text-right min-w-[120px]">
                      {t("common.actions")}
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {templateList.map((template) => (
                    <TableRow key={template.id}>
                      <TableCell className="font-medium">
                        <div className="flex flex-col">
                          <span>{localizedName(template.name)}</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="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>
                          <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 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"
                            title={t("contentManagement.deleteTemplate")}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

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

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

      {/* View Dialog */}
      <Dialog open={isViewDialogOpen} onOpenChange={setIsViewDialogOpen}>
        <DialogContent className="max-w-[95vw] lg:max-w-[1200px] max-h-[90vh] overflow-y-auto w-full">
          <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="text-sm text-gray-900 dark:text-gray-100 mt-1">
                  {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="text-sm text-gray-900 dark:text-gray-100 mt-1">
                  {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="text-sm text-gray-900 dark:text-gray-100 mt-1 p-3 border border-gray-200 dark:border-gray-700 rounded-md bg-gray-50 dark:bg-gray-700 max-h-60 overflow-y-auto"
                  dangerouslySetInnerHTML={{ __html: sanitizeHtml(selectedTemplate.body) }}
                />
              </div>
              <div className="flex justify-end">
                <Button onClick={() => setIsViewDialogOpen(false)}>
                  {t("common.close")}
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t("contentManagement.deleteTemplate")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t("contentManagement.deleteTemplateConfirm", {
                name: selectedTemplate
                  ? localizedName(selectedTemplate.name)
                  : "",
              })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              disabled={isDeletingTemplate}
              className="bg-red-600 hover:bg-red-700"
            >
              {isDeletingTemplate ? t("common.deleting") : t("common.delete")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
};

export default TemplateTable;
