import { useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  useTemplates,
  useTemplateMutations,
  useResourceTypes,
} from "../hooks/useTemplates";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { Edit2, Trash2, Plus } from "lucide-react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";

export const TemplateList = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [search, setSearch] = useState("");
  const [selectedResourceTypeId, setSelectedResourceTypeId] =
    useState<string>("");
  const [selectedTemplate, setSelectedTemplate] = useState<any>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);

  const { data: templatesData, isLoading } = useTemplates({
    search,
    resourceTypeId: selectedResourceTypeId,
  });
  const { data: resourceTypesData } = useResourceTypes();
  const { delete: deleteTemplate } = useTemplateMutations();

  const getResourceTypeName = (typeId: string) => {
    return (
      resourceTypesData?.items?.find((t) => t.id === typeId)?.name?.en || typeId
    );
  };

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

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

    deleteTemplate.mutate(selectedTemplate.id, {
      onSuccess: () => {
        setIsDeleteDialogOpen(false);
        setSelectedTemplate(null);
        toast.success(t("template.deleted", "Template deleted successfully"));
      },
      onError: (error: any) => {
        toast.error(
          error.message ||
            t("template.deleteFailed", "Failed to delete template"),
        );
      },
    });
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">
            {t("template.title", "Resource Configuration")}
          </h2>
          <p className="text-gray-600 mt-1">
            {t("template.pageDescription", "Manage resources for style settings")}
          </p>
        </div>
        <Button
          onClick={() =>
            navigate(
              "/user-management/web-management/TemplateConfiguration/new",
            )
          }
          className="bg-purple-600 hover:bg-purple-700 text-white gap-2"
        >
          <Plus className="h-4 w-4" />
          {t("template.create", "Create Resource")}
        </Button>
      </div>

      {/* Search and Filter */}
      <div className="flex flex-col md:flex-row gap-4">
        <div className="flex-1">
          <Input
            placeholder={t("template.search", "Search templates...")}
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            disabled={!selectedResourceTypeId}
            className="max-w-sm"
          />
        </div>
        <div className="w-full md:w-64">
          <Select
            value={selectedResourceTypeId}
            onValueChange={setSelectedResourceTypeId}
          >
            <SelectTrigger>
              <SelectValue
                placeholder={t(
                  "template.selectResourceType",
                  "Select resource type",
                )}
              />
            </SelectTrigger>
            <SelectContent>
              {resourceTypesData?.items?.map((type) => (
                <SelectItem key={type.id} value={type.id}>
                  {type.name.en} ({type.name.am})
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="bg-gray-50 border-b border-gray-200">
                <TableHead className="text-gray-700 font-semibold">
                  {t("template.name", "Name")}
                </TableHead>
                <TableHead className="text-gray-700 font-semibold">
                  {t("template.resourceType", "Resource Type")}
                </TableHead>
                <TableHead className="text-gray-700 font-semibold">
                  {t("template.description", "Description")}
                </TableHead>
                <TableHead className="text-gray-700 font-semibold">
                  {t("template.file", "File")}
                </TableHead>
                <TableHead className="text-gray-700 font-semibold text-right">
                  {t("common.actions", "Actions")}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {!selectedResourceTypeId ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center py-8">
                    <div className="flex flex-col items-center justify-center">
                      <p className="text-gray-500 font-medium">
                        {t(
                          "template.selectTypeFirst",
                          "Select a resource type to view templates",
                        )}
                      </p>
                    </div>
                  </TableCell>
                </TableRow>
              ) : isLoading ? (
                Array.from({ length: 5 }).map((_, i) => (
                  <TableRow key={i}>
                    <TableCell>
                      <Skeleton className="h-4 w-32" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-24" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-40" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-20" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-24" />
                    </TableCell>
                  </TableRow>
                ))
              ) : templatesData?.items?.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center py-8">
                    <div className="flex flex-col items-center justify-center">
                      <p className="text-gray-500 font-medium">
                        {t("template.noTemplates", "No templates yet")}
                      </p>
                      <p className="text-gray-400 text-sm mt-1">
                        {t(
                          "template.getStarted",
                          "Get started by creating your first template",
                        )}
                      </p>
                    </div>
                  </TableCell>
                </TableRow>
              ) : (
                templatesData?.items?.map((template) => (
                  <TableRow
                    key={template.id}
                    className="border-b border-gray-100 hover:bg-gray-50"
                  >
                    <TableCell className="font-medium text-gray-900">
                      {template.name?.en || "-"}
                    </TableCell>
                    <TableCell className="text-gray-600">
                      {getResourceTypeName(template.resourceTypeId)}
                    </TableCell>
                    <TableCell className="text-gray-600 max-w-xs truncate">
                      {template.description?.en || "-"}
                    </TableCell>
                    <TableCell className="text-gray-600">
                      {template.fileInfo?.originalname ? (
                        <span className="text-primary-600 hover:text-primary-700 cursor-pointer">
                          {template.fileInfo.originalname}
                        </span>
                      ) : (
                        <span className="text-gray-400">-</span>
                      )}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <button
                          onClick={() =>
                            navigate(
                              `/user-management/web-management/TemplateConfiguration/edit/${template.id}`,
                              {
                                state: {
                                  resourceTypeId: template.resourceTypeId,
                                },
                              },
                            )
                          }
                          className="p-2 text-purple-600 hover:bg-purple-50 rounded-lg transition-colors"
                          title={t("common.edit", "Edit")}
                        >
                          <Edit2 className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => handleDelete(template)}
                          className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                          title={t("common.delete", "Delete")}
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </div>

      {/* Delete Dialog */}
      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t("template.confirmDelete", "Confirm Deletion")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t(
                "template.deleteConfirmation",
                "Are you sure you want to delete this template? This action cannot be undone.",
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <div className="flex justify-end gap-3">
            <AlertDialogCancel>
              {t("common.cancel", "Cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              disabled={deleteTemplate.isPending}
              className="bg-red-600 hover:bg-red-700"
            >
              {deleteTemplate.isPending ? (
                <span className="flex items-center gap-2">
                  <span className="animate-spin">⏳</span>
                  {t("common.deleting", "Deleting...")}
                </span>
              ) : (
                t("common.delete", "Delete")
              )}
            </AlertDialogAction>
          </div>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};
