import { useForm } from "react-hook-form";
import { Button } from "@/shared/common/ui/button";
import { Label } from "@/shared/common/ui/label";
import { Input } from "@/shared/common/ui/input";
import { Loader2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  useTemplateSettingValue,
  useTemplateSettingValueMutations,
  useTemplates,
  useTemplateSettings,
  useResources,
  useResourceTypes,
} from "./hooks/useTemplateSettingValues";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";

interface FormData {
  templateSettingId: string;
  resourceId: string;
  value: string;
}

export const TemplateSettingValueForm = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<string>("");
  const [selectedResourceType, setSelectedResourceType] = useState<string>("");

  const { data: templateSettingValue, isLoading: isLoadingTemplate } =
    useTemplateSettingValue(id || "");
  const { data: templatesData } = useTemplates();
  const { data: templateSettingsData } = useTemplateSettings(selectedTemplate);
  const { data: resourcesData } = useResources(selectedResourceType);
  const { data: resourceTypesData } = useResourceTypes();
  const { create, update } = useTemplateSettingValueMutations();

  const defaultValues = useMemo(
    () => ({
      templateSettingId: templateSettingValue?.templateSettingId || "",
      resourceId: templateSettingValue?.resourceId || "",
      value: templateSettingValue?.value || "",
    }),
    [templateSettingValue],
  );

  const {
    register,
    handleSubmit,
    reset,
    setValue,
    formState: { errors },
  } = useForm<FormData>({
    defaultValues,
  });

  useEffect(() => {
    if (templateSettingValue) {
      reset(defaultValues);
      setSelectedTemplate(templateSettingValue.templateSettingId);
    }
  }, [templateSettingValue, defaultValues, reset]);

  const handleFormSubmit = async (formData: FormData) => {
    setIsSubmitting(true);
    try {
      if (id) {
        await update.mutateAsync({
          id,
          data: formData,
        });
        toast.success(
          t(
            "templateSettingValue.updated",
            "Template setting value updated successfully",
          ),
        );
      } else {
        await create.mutateAsync(formData);
        toast.success(
          t(
            "templateSettingValue.created",
            "Template setting value created successfully",
          ),
        );
      }

      navigate("/user-management/web-management/TemplateSettingValues/values");
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : "Unknown error";
      toast.error(
        errorMessage ||
          t(
            "templateSettingValue.error",
            "Failed to save template setting value",
          ),
      );
      console.error("Form submission error:", error);
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isLoadingTemplate) {
    return (
      <div className="flex items-center justify-center p-8">
        <Loader2 className="h-8 w-8 animate-spin text-purple-600" />
      </div>
    );
  }

  return (
    <div className="max-h-[80vh] overflow-y-auto p-6 bg-white rounded-xl border border-gray-200 shadow-sm">
      <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-6">
        {/* Header */}
        <div className="mb-6">
          <h2 className="text-2xl font-bold text-gray-900">
            {id
              ? t("templateSettingValue.edit", "Edit Template Setting Value")
              : t(
                  "templateSettingValue.create",
                  "Create Template Setting Value",
                )}
          </h2>
          <p className="text-gray-600 mt-1">
            {id
              ? t(
                  "templateSettingValue.editDescription",
                  "Update template setting value",
                )
              : t(
                  "templateSettingValue.createDescription",
                  "Create a new template setting value",
                )}
          </p>
        </div>

        {/* Form Fields */}
        <div className="space-y-4">
          {/* Template Dropdown */}
          <div className="space-y-2">
            <Label htmlFor="template" className="text-gray-700">
              {t("templateSettingValue.template", "Template")} *
            </Label>
            <Select
              value={selectedTemplate}
              onValueChange={(value) => {
                setSelectedTemplate(value);
                setValue("templateSettingId", value);
              }}
            >
              <SelectTrigger className="w-full">
                <SelectValue
                  placeholder={t(
                    "templateSettingValue.selectTemplate",
                    "Select template",
                  )}
                />
              </SelectTrigger>
              <SelectContent>
                {Array.isArray(templatesData?.items) &&
                  templatesData.items.map((template: any) => (
                    <SelectItem key={template.id} value={template.id}>
                      {template.name?.en || template.name}
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
            {errors.templateSettingId && (
              <p className="text-red-500 text-sm">
                {errors.templateSettingId.message}
              </p>
            )}
          </div>

          {/* Template Settings Dropdown */}
          <div className="space-y-2">
            <Label htmlFor="templateSetting" className="text-gray-700">
              {t("templateSettingValue.templateSetting", "Template Setting")} *
            </Label>
            <Select
              value={defaultValues.templateSettingId}
              onValueChange={(value) => {
                setValue("templateSettingId", value);
              }}
              disabled={!selectedTemplate}
            >
              <SelectTrigger className="w-full">
                <SelectValue
                  placeholder={t(
                    "templateSettingValue.selectTemplateSetting",
                    "Select template setting",
                  )}
                />
              </SelectTrigger>
              <SelectContent>
                {Array.isArray(templateSettingsData?.items) &&
                  templateSettingsData.items.map((setting: any) => (
                    <SelectItem key={setting.id} value={setting.id}>
                      {setting.name?.en || setting.name}
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
          </div>

          {/* Resource Type Dropdown */}
          <div className="space-y-2">
            <Label htmlFor="resourceType" className="text-gray-700">
              {t("templateSettingValue.resourceType", "Resource Type")} *
            </Label>
            <Select
              value={selectedResourceType}
              onValueChange={(value) => {
                setSelectedResourceType(value);
              }}
            >
              <SelectTrigger className="w-full">
                <SelectValue
                  placeholder={t(
                    "templateSettingValue.selectResourceType",
                    "Select resource type",
                  )}
                />
              </SelectTrigger>
              <SelectContent>
                {Array.isArray(resourceTypesData?.items) &&
                  resourceTypesData.items.map((resourceType: any) => (
                    <SelectItem key={resourceType.id} value={resourceType.id}>
                      {resourceType.name?.en || resourceType.name}
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
          </div>

          {/* Resource Dropdown */}
          <div className="space-y-2">
            <Label htmlFor="resource" className="text-gray-700">
              {t("templateSettingValue.resource", "Resource")} *
            </Label>
            <Select
              value={defaultValues.resourceId}
              onValueChange={(value) => {
                setValue("resourceId", value);
              }}
              disabled={!selectedResourceType}
            >
              <SelectTrigger className="w-full">
                <SelectValue
                  placeholder={t(
                    "templateSettingValue.selectResource",
                    "Select resource",
                  )}
                />
              </SelectTrigger>
              <SelectContent>
                {Array.isArray(resourcesData?.items) &&
                  resourcesData.items.map((resource: any) => (
                    <SelectItem key={resource.id} value={resource.id}>
                      {resource.name?.en || resource.name}
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
            {errors.resourceId && (
              <p className="text-red-500 text-sm">
                {errors.resourceId.message}
              </p>
            )}
          </div>

          {/* Value Input */}
          <div className="space-y-2">
            <Label htmlFor="value" className="text-gray-700">
              {t("templateSettingValue.value", "Value")} *
            </Label>
            <Input
              id="value"
              placeholder={t("templateSettingValue.enterValue", "Enter value")}
              {...register("value", {
                required: t(
                  "templateSettingValue.valueRequired",
                  "Value is required",
                ),
              })}
              className="border-gray-300"
            />
            {errors.value && (
              <p className="text-red-500 text-sm">{errors.value.message}</p>
            )}
          </div>
        </div>

        {/* Actions */}
        <div className="flex justify-end gap-3 pt-6 border-t border-gray-200">
          <Button
            type="button"
            variant="outline"
            onClick={() =>
              navigate(
                "/user-management/web-management/TemplateSettingValues/values",
              )
            }
            className="px-6"
          >
            {t("common.cancel", "Cancel")}
          </Button>
          <Button
            type="submit"
            disabled={isSubmitting}
            className="px-6 bg-purple-600 hover:bg-purple-700 text-white"
          >
            {isSubmitting ? (
              <span className="flex items-center gap-2">
                <Loader2 className="w-4 h-4 animate-spin" />
                {t("common.saving", "Saving...")}
              </span>
            ) : (
              t("common.save", "Save")
            )}
          </Button>
        </div>
      </form>
    </div>
  );
};
