
"use client";
import Button from "@/components/ui/Button";
import InputField from "@/components/ui/Input";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useForm } from "react-hook-form";
import { use, useEffect, useState } from "react";
import { useAuthStore } from "@/zustand/auth/useAuthStore";
import { getDictionary } from "@/utils/getDictionary";
import { SettingsContent } from "@/types/staticContent/settings.content.type";
import { getClientDictionary } from "@/utils/getClientDictionary";

type ProfileFormValues = {
  first_name: string;
  last_name: string;
  email: string;
  username: string;
  profile_picture: FileList;
};


const ProfilePage = () => {
  const { viewProfile, updateProfile, profileDetails, language } = useAuthStore();
  const SETTINGS = getClientDictionary(language, 'settings') as SettingsContent;

  const [preview, setPreview] = useState<string | null>(null);
  const [isEdit, setIsEdit] = useState(false);
  const [imageChanged, setImageChanged] = useState(false);
  const [imageRemoved, setImageRemoved] = useState(false);
  const [originalImageUrl, setOriginalImageUrl] = useState<string | null>(null);


  const profileSchema = yup.object({
    profile_picture: yup
      .mixed<FileList>()
      .nullable()
      .test("fileSize", SETTINGS.SETTINGS.FORM.FILE_TOO_LARGE, (value) => {
        if (!value || value.length === 0) return true;
        return value[0].size <= 2_000_000;
      })
      .test("fileType", SETTINGS.SETTINGS.FORM.FILE_TYPE_INVALID, (value) => {
        if (!value || value.length === 0) return true;
        return ["image/jpeg", "image/png", "image/webp"].includes(value[0].type);
      }),
    first_name: yup.string().required(SETTINGS.SETTINGS.FORM.FIRST_NAME_REQUIRED),
    last_name: yup.string().required(SETTINGS.SETTINGS.FORM.LAST_NAME_REQUIRED),
    username: yup.string().required(SETTINGS.SETTINGS.FORM.USERNAME_REQUIRED),
    email: yup
      .string()
      .required(SETTINGS.SETTINGS.FORM.EMAIL_REQUIRED)
      .matches(
        /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
        SETTINGS.SETTINGS.FORM.EMAIL_REQUIRED
      ),
  });

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    reset,
    getValues,
    formState: { errors },
  } = useForm<any>({
    resolver: yupResolver(profileSchema),
    defaultValues: {
      first_name: "",
      last_name: "",
      email: "",
      username: "",
      profile_picture: undefined as any,
    },
  });

  useEffect(() => {
    viewProfile();
  }, [])

  // Load profile data once
  useEffect(() => {
    if (profileDetails) {
      reset({
        first_name: profileDetails.first_name || "",
        last_name: profileDetails.last_name || "",
        email: profileDetails.email || "",
        username: profileDetails.username || "",
        profile_picture: undefined,
      });

      // Store original image URL and show it as preview
      if (profileDetails.profile_picture) {
        setOriginalImageUrl(profileDetails.profile_picture);
        setPreview(profileDetails.profile_picture);
      } else {
        setOriginalImageUrl(null);
        setPreview(null);
      }

      // Reset flags when profile loads
      setImageChanged(false);
      setImageRemoved(false);
    }
  }, [profileDetails, reset]);

  // Watch file input (only new files)
  const profile_picture = watch("profile_picture");

  // Preview for newly selected file
  useEffect(() => {
    if (profile_picture && profile_picture.length > 0) {
      const file = profile_picture[0];
      try {
        const url = URL.createObjectURL(file);
        setPreview(url);
        setImageChanged(true);
        setImageRemoved(false);
        return () => URL.revokeObjectURL(url);
      } catch (err) {
        console.error("createObjectURL failed", err);
        setPreview(null);
      }
    }
  }, [profile_picture]);


      useEffect(() => {
        // Forces form to re-validate with new resolver
        reset(
            {
                first_name: getValues("first_name"),
                last_name: getValues("last_name"),
                email: getValues("email"),
                username: getValues("username"),
                profile_picture: getValues("profile_picture"),
            },
            { keepValues: true, keepDirty: true }
        )
    }, [language, reset, getValues])
  const removeImage = () => {
    setValue("profile_picture", null as any, { shouldValidate: true });
    setPreview(null);
    setImageRemoved(true);
    setImageChanged(false);
  };

  const onSubmit = (data: ProfileFormValues) => {
    const formData = new FormData();

    formData.append("first_name", data.first_name);
    formData.append("last_name", data.last_name);
    formData.append("email", data.email);
    formData.append("username", data.username);

    /**
     * profile_picture handling
     */
    if (imageChanged && data.profile_picture?.[0]) {
      // ✅ New file selected
      formData.append("profile_picture", data.profile_picture[0]);
    }
    else if (imageRemoved) {
      // ✅ Image removed → send empty file (0 bytes)
      const emptyFile = new File([], "removed.jpg");
      formData.append("profile_picture", emptyFile);
    }
    // ❌ If not changed → do nothing (key not added)

    if (isEdit) {
      updateProfile(formData, (success) => {
        if (success) {
          setIsEdit(false);
          setImageChanged(false);
          setImageRemoved(false);
          viewProfile();
        }
      }, true);
    }
  };


  return (
    <div className="flex flex-col gap-5 sm:gap-6 md:gap-7 xl:gap-8">
      <div className="w-full flex gap-4 justify-between items-center">
        <p className="text-lg lg:text-xl font-medium text-light">{SETTINGS.SETTINGS.TITLE}</p>
      </div>

      <form onSubmit={handleSubmit(onSubmit)}>
        {/* Avatar */}
        <div className="relative w-16 h-16 lg:w-[90px] lg:h-[90px] bg-secondary25 border border-grey32 rounded-full flex justify-center items-center mb-4 lg:mb-6 2xl:mb-10">
          {preview ? (
            <>
              <img
                src={preview}
                alt="Profile preview"
                className="w-full h-full object-cover rounded-full"
              />

              {isEdit && (
                <button
                  type="button"
                  onClick={removeImage}
                  className="absolute top-0.5 lg:top-1 right-0.5 lg:right-1 bg-black rounded-full w-4.5 h-4.5 lg:w-5.5 lg:h-5.5 flex justify-center items-center cursor-pointer hover:bg-primary duration-300"
                >
                  <i className="icon icon-close w-3.5 h-3.5 lg:w-4.5 lg:h-4.5 bg-white" />
                </button>
              )}
            </>
          ) : (
            <>
              <i className="icon icon-user w-6 lg:w-8 h-6 lg:h-8 bg-light"></i>

              <button
                type="button"
                disabled={!isEdit}
                className="bg-primary w-5 lg:w-7.5 h-5 lg:h-7.5 rounded-full absolute bottom-0 right-0 flex justify-center items-center cursor-pointer"
              >
                {isEdit && <i className="icon icon-camera w-3.5 lg:w-4 h-3.5 lg:h-4 bg-white"></i>}
                <input
                  type="file"
                  accept="image/jpeg,image/png,image/webp"
                  {...register("profile_picture")}
                  className="w-full h-full opacity-0 cursor-pointer absolute inset-0"
                  disabled={!isEdit}
                />
              </button>
            </>
          )}
        </div>

        {errors.profile_picture && (
          <p className="text-red-500 text-xs text-start mb-4">
            {errors.profile_picture.message as string}
          </p>
        )}

        <div className="flex flex-col md:flex-row gap-x-4">
          <InputField
            label={SETTINGS.SETTINGS.FORM.FIRST_NAME}
            placeholder={SETTINGS.SETTINGS.FORM.FIRST_NAME}
            {...register("first_name")}
            error={errors.first_name}
            disabled={!isEdit}
          />
          <InputField
            label={SETTINGS.SETTINGS.FORM.LAST_NAME}
            placeholder={SETTINGS.SETTINGS.FORM.LAST_NAME}
            {...register("last_name")}
            error={errors.last_name}
            disabled={!isEdit}
          />
        </div>

        <InputField
          type="email"
          label={SETTINGS.SETTINGS.FORM.EMAIL_ADDRESS}
          placeholder={SETTINGS.SETTINGS.FORM.EMAIL_ADDRESS}
          disabled
          {...register("email")}
          error={errors.email}
          readOnly
        />

        <InputField
          label={SETTINGS.SETTINGS.FORM.USERNAME}
          placeholder={SETTINGS.SETTINGS.FORM.USERNAME}
          disabled
          {...register("username")}
          error={errors.username}
          readOnly
        />

        <div className="flex justify-end">
          {isEdit ? (
            <Button
              type="submit"
              className="w-fit! min-w-[100px] md:min-w-[142px]"
              variant="primary"
            >
              {SETTINGS.SETTINGS.FORM.SAVE_CHANGES}
            </Button>
          ) : (
            <Button
              type="button"
              className="w-fit! min-w-[100px] md:min-w-[142px]"
              onClick={(e: React.MouseEvent) => {
                e.preventDefault();
                setIsEdit(true);
              }}
              variant="primary"
            >
              {SETTINGS.SETTINGS.PROFILE.EDIT_PROFILE}
            </Button>
          )}
        </div>
      </form>
    </div>
  );
};

export default ProfilePage;