import { useState } from "react";
import { useNavigate } from "react-router-dom";
import {
  useTemplateSettingValues,
  useTemplateSettingValueMutations,
  useTemplateSettings,
  useTemplates,
} from "./hooks/useTemplateSettingValues";
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";
import { Label } from "@/shared/common/ui/label";

export const TemplateSettingValueList = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [search, setSearch] = useState("");
  const [selectedTemplate, setSelectedTemplate] = useState<string>("");
  const [selectedTemplateSetting, setSelectedTemplateSetting] =
    useState<string>("");
  const [selectedValue, setSelectedValue] = useState<any>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);

  const { data: templatesData } = useTemplates();
  const { data: templateSettingsData } = useTemplateSettings(selectedTemplate);
  const { data: valuesData, isLoading } = useTemplateSettingValues(
    selectedTemplateSetting,
    { search },
  );
  const { delete: deleteValue } = useTemplateSettingValueMutations();

  const handleDelete = (value: any) => {
    setSelectedValue(value);
    setIsDeleteDialogOpen(true);
  };

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

    deleteValue.mutate(selectedValue.id, {
      onSuccess: () => {
        setIsDeleteDialogOpen(false);
        setSelectedValue(null);
        toast.success(
          t(
            "templateSettingValue.deleted",
            "Template setting value deleted successfully",
          ),
        );
      },
      onError: (error: any) => {
        toast.error(
          error.message ||
            t(
              "templateSettingValue.deleteFailed",
              "Failed to delete template setting value",
            ),
        );
      },
    });
  };

  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("templateSettingValue.title", "Template Setting Values")}
          </h2>
          <p className="text-gray-600 mt-1">
            {t(
              "templateSettingValue.description",
              "Manage template setting values",
            )}
          </p>
        </div>
        <Button
          onClick={() =>
            navigate(
              "/user-management/web-management/TemplateSettingValues/new",
            )
          }
          className="bg-purple-600 hover:bg-purple-700 text-white gap-2"
        >
          <Plus className="h-4 w-4" />
          {t("templateSettingValue.create", "Create Template Setting Value")}
        </Button>
      </div>

      {/* Search and Filter */}
      <div className="flex flex-col md:flex-row gap-4">
        <Input
          placeholder={t(
            "templateSettingValue.searchByValue",
            "Search by value...",
          )}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="max-w-sm"
        />
        <div className="space-y-2 md:w-64">
          <Label htmlFor="template" className="text-gray-700">
            {t("templateSettingValue.template", "Template")}
          </Label>
          <Select
            value={selectedTemplate}
            onValueChange={(value) => {
              setSelectedTemplate(value);
              setSelectedTemplateSetting("");
            }}
          >
            <SelectTrigger className="w-full">
              <SelectValue
                placeholder={t(
                  "templateSettingValue.selectTemplate",
                  "Select template",
                )}
              />
            </SelectTrigger>
            <SelectContent>
              {Array.isArray(templatesData?.items) &&
                templatesData.items
                  .filter(
                    (template: any) =>
                      template &&
                      typeof template === "object" &&
                      "id" in template,
                  )
                  .map((template: any) => (
                    <SelectItem key={template.id} value={template.id}>
                      {String(template.name?.en || template.name || "")}
                    </SelectItem>
                  ))}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-2 md:w-64">
          <Label htmlFor="templateSetting" className="text-gray-700">
            {t("templateSettingValue.templateSetting", "Template Setting")} *
          </Label>
          <Select
            value={selectedTemplateSetting}
            onValueChange={(value) => {
              setSelectedTemplateSetting(value);
            }}
            disabled={!selectedTemplate}
          >
            <SelectTrigger className="w-full">
              <SelectValue
                placeholder={t(
                  "templateSettingValue.selectTemplateSetting",
                  "Select template setting",
                )}
              />
            </SelectTrigger>
            <SelectContent>
              {Array.isArray(templateSettingsData?.items) &&
                templateSettingsData.items
                  .filter(
                    (setting: any) =>
                      setting && typeof setting === "object" && "id" in setting,
                  )
                  .map((setting: any) => (
                    <SelectItem key={setting.id} value={setting.id}>
                      {String(setting.name?.en || setting.name || "")}
                    </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("templateSettingValue.template", "Template")}
                </TableHead>
                <TableHead className="text-gray-700 font-semibold">
                  {t(
                    "templateSettingValue.templateSetting",
                    "Template Setting",
                  )}
                </TableHead>
                <TableHead className="text-gray-700 font-semibold">
                  {t("templateSettingValue.value", "Value")}
                </TableHead>
                <TableHead className="text-gray-700 font-semibold text-right">
                  {t("common.actions", "Actions")}
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 5 }).map((_, i) => (
                  <TableRow key={i}>
                    <TableCell>
                      <Skeleton className="h-4 w-32" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-32" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-40" />
                    </TableCell>
                    <TableCell>
                      <Skeleton className="h-4 w-24" />
                    </TableCell>
                  </TableRow>
                ))
              ) : !Array.isArray(valuesData?.items) ||
                valuesData.items.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={4} className="text-center py-8">
                    <div className="flex flex-col items-center justify-center">
                      <p className="text-gray-500 font-medium">
                        {t(
                          "templateSettingValue.noValues",
                          "No template setting values yet",
                        )}
                      </p>
                      <p className="text-gray-400 text-sm mt-1">
                        {t(
                          "templateSettingValue.getStarted",
                          "Get started by creating your first template setting value",
                        )}
                      </p>
                    </div>
                  </TableCell>
                </TableRow>
              ) : (
                Array.isArray(valuesData.items) &&
                valuesData.items.map((value) => (
                  <TableRow
                    key={value.id}
                    className="border-b border-gray-100 hover:bg-gray-50"
                  >
                    <TableCell className="font-medium text-gray-900">
                      {String(value.templateName || "")}
                    </TableCell>
                    <TableCell className="text-gray-600">
                      {String(value.templateSettingName || "")}
                    </TableCell>
                    <TableCell className="text-gray-600 max-w-xs truncate">
                      {String(value.value || "")}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <button
                          onClick={() =>
                            navigate(
                              `/user-management/web-management/TemplateSettingValues/edit/${value.id}`,
                            )
                          }
                          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(value)}
                          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("templateSettingValue.confirmDelete", "Confirm Deletion")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t(
                "templateSettingValue.deleteConfirmation",
                "Are you sure you want to delete this template setting value? This action cannot be undone.",
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <div className="flex justify-end gap-3">
            <AlertDialogCancel>
              {t("common.cancel", "Cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              disabled={deleteValue.isPending}
              className="bg-red-600 hover:bg-red-700"
            >
              {deleteValue.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>
  );
};
