import { useForm } from "react-hook-form";
import { Button } from "@/shared/common/ui/button";
import { Label } from "@/shared/common/ui/label";
import { ImageIcon, Loader2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { FormFeild } from "../components/FormFeild";
import { CreateThemePayload } from "../types/themeTypes";
import { useNavigate, useParams } from "react-router-dom";
import { useTheme } from "../hooks/useTheme";
import { toast } from "sonner";
import { ImageUpload, Section } from "../components/FormInputBox";
interface FormData {
  primaryColor: {
    type: string;
    value: string;
  };
  SecondaryColor: {
    type: string;
    value: string;
  };
  image: FileList;
  isActive: boolean;
}
export const EditTheme = () => {
  const { id } = useParams();
  const { items: item, createItem } = useTheme();
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const navigate = useNavigate();
  const defaultValues = useMemo(
    () => ({
      primaryColor: {
        type: "PRIMARY_COLOR",
        value: item?.find((i) => i.type === "PRIMARY_COLOR")?.value,
      },
      SecondaryColor: {
        type: "SECONDARY_COLOR",
        value: item?.find((i) => i.type === "SECONDARY_COLOR")?.value,
      },
      isActive: true,
      image: undefined,
    }),
    [item] // 👈 recompute only when item changes
  );
  const {
    register,
    handleSubmit,
    watch,
    reset,
    formState: { errors },
  } = useForm<FormData>({
    defaultValues,
  });
  useEffect(() => {
    if (item) {
      reset(defaultValues);
    }
  }, [item, defaultValues, reset]);
  const imageFile = watch("image")?.[0];
  const [imagePreview, setImage1Preview] = useState<string>(
    item?.find((i) => i.type === "LOGO")?.presigned || ""
  );
  useEffect(() => {
    const logoItem = item?.find((i) => i.type === "LOGO");
    if (logoItem?.presigned) {
      setImage1Preview(logoItem.presigned);
    }
  }, [item]);
  useEffect(() => {
    if (imageFile) {
      const url = URL.createObjectURL(imageFile);
      setImage1Preview(url);
      return () => URL.revokeObjectURL(url);
    }
  }, [imageFile]);

  const handleEditSubmit = async (formData: FormData) => {
    if (!item) return;
    setIsSubmitting(true);
    try {
      const imageFile = formData.image?.[0];
      const payload: CreateThemePayload = [
        {
          type: formData.primaryColor.type,
          value: formData.primaryColor.value,
          fileInfo: undefined,
          isActive: true,
          id: item.find((i) => i.type === "PRIMARY_COLOR")?.id || undefined,
        },
        {
          type: formData.SecondaryColor.type,
          value: formData.SecondaryColor.value,
          fileInfo: undefined,
          isActive: true,
          id: item.find((i) => i.type === "SECONDARY_COLOR")?.id || undefined,
        },
        {
          type: "LOGO",
          value: "",
          fileInfo: imageFile
            ? {
                fileName: imageFile.name,
                contentType: imageFile.type,
                size: imageFile.size,
                originalname: imageFile.name,
              }
            : undefined,
          isActive: true,
          id: item.find((i) => i.type === "LOGO")?.id || undefined,
        },
      ];

      await createItem({
        data: payload,
        ...(imageFile && { imageFile }),
      });

      toast.success("Theme saved successfully");
      setIsSubmitting(false);
    } catch (error) {
      toast.error("Failed to update about us");
      console.error("Update error:", error);
      setIsSubmitting(false);
    }
  };
  return (
    <div className="max-h-[80vh] overflow-y-auto p-6 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm">
      <form onSubmit={handleSubmit(handleEditSubmit)} className="space-y-8">
        {/* Title Section */}
        <div className="bg-gray-50 dark:bg-gray-700 p-5 rounded-lg border border-gray-100 dark:border-gray-600">
          <h3 className="text-lg font-semibold text-gray-800 dark:text-gray-200 mb-4 flex items-center">
            <div className="h-1 w-4 bg-primary-500 mr-2 rounded-full"></div>
            Color
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label htmlFor="ThemeTitleAm" className="text-gray-700 dark:text-gray-300">
                Primary color
              </Label>
              <div className="flex items-center gap-3">
                <input
                  id="color"
                  type="color"
                  {...register("primaryColor.value", {
                    required: "Color is required",
                  })}
                  className="h-10 w-16 cursor-pointer border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-600"
                />
                <span className="text-sm text-gray-600 dark:text-gray-400 font-mono">
                  {watch("primaryColor.value") || "#000000"}
                </span>
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="ThemeTitleEn" className="text-gray-700 dark:text-gray-300">
                secondary color
              </Label>
              <div className="flex items-center gap-3">
                <input
                  id="color"
                  type="color"
                  {...register("SecondaryColor.value", {
                    required: "Color is required",
                  })}
                  className="h-10 w-16 cursor-pointer border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-600"
                />
                <span className="text-sm text-gray-600 dark:text-gray-400 font-mono">
                  {watch("SecondaryColor.value") || "#000000"}
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* Image Upload */}
        <Section title="Image">
          <ImageUpload
            label="Experience Image*"
            preview={imagePreview}
            existingName={
              item?.find((i) => i.type === "LOGO")?.fileInfo?.originalname
            }
            register={register("image")}
            error={errors.image?.message}
            onView={() => window.open(imagePreview, "_blank")}
            id="image"
            isRequired={false}
          />
        </Section>

        {/* Actions */}
        <div className="flex justify-end gap-3 pt-6 border-t border-gray-200 dark:border-gray-700">
          <Button
            type="submit"
            disabled={isSubmitting}
            className="px-6 py-2 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" />
                saving...
              </span>
            ) : (
              "save"
            )}
          </Button>
        </div>
      </form>
    </div>
  );
};
