"use client";

import { ChangeEvent, FormEvent, useRef, useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { FiCamera, FiMail, FiUser } from "react-icons/fi";
import { BiArrowBack } from "react-icons/bi";

import CustomInput from "../../../../components/ui/CustomInput";
import CustomPhoneInput from "../../../../components/ui/CustomPhoneInput";
import Button from "../../../../components/ui/Button";
import { useAppForm } from "../../../../hooks/useAppForm";
import {
  editProfileSchema,
  EditProfileSchema,
} from "../../../../hooks/features/profile/edit-profile/schema";
import { useAppSelector } from "../../../../hooks/useAppRedux";
import useEditProfile from "../../../../hooks/features/profile/edit-profile/useEditProfile";
import { useModal } from "../../../../lib/modal-system/ModalContext";
import useSendEmailToExisting from "../../../../hooks/features/profile/email/useSendEmailToExisting";

export default function EditProfilePage() {
  const router = useRouter();
  const profile = useAppSelector((state) => state.user.user);
  const { handleEditProfile, loading } = useEditProfile();
  const { openModal } = useModal();
  const { handleSendEmailToExisting, loading: sendingMail } =
    useSendEmailToExisting();

  const { control, errors, register, handleSubmit, reset, getValue } =
    useAppForm<EditProfileSchema>({
      defaultValues: {
        mobileNumber: {
          dialCode: profile.dialCode,
          number: profile.mobileNumber,
        },
        firstName: profile.firstName,
        lastName: profile.lastName,
        email: profile.email,
      },
      schema: editProfileSchema,
      onSubmit: async (data) => {
        try {
          await handleEditProfile(data);

          reset();
          router.back();
        } catch (error) {
          console.log(error);
        }
      },
    });

  const fileRef = useRef<HTMLInputElement>(null);

  const [profileImage, setProfileImage] = useState("/images/user.png");

  const handleImageChange = (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];

    if (!file) return;

    const imageUrl = URL.createObjectURL(file);
    setProfileImage(imageUrl);
  };

  //   const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
  //     e.preventDefault();

  //     const formData = new FormData();

  //     formData.append("firstName", "Jenny");
  //     formData.append("lastName", "Lopez");
  //     formData.append("phone", phone);

  //     const selectedImage = fileRef.current?.files?.[0];

  //     if (selectedImage) {
  //       formData.append("profileImage", selectedImage);
  //     }

  //     console.log("Profile updated", {
  //       phone,
  //       image: selectedImage,
  //     });
  //   };

  const handleEmailChange = async () => {
    try {
      //   await handleSendEmailToExisting();
      openModal("UPDATE_EMAIL_CONFIRMATION", {
        email: profile.email,
      });
    } catch (error) {}
  };

  return (
    <div className="mx-auto max-w-188.5">
      <div className="glass-card-v2 rounded-2xl p-6 md:p-7.5">
        <div className="relative z-10">
          <div className="mb-8 flex items-center gap-4">
            <button
              type="button"
              onClick={() => router.back()}
              className="flex cursor-pointer items-center gap-3 text-link-1"
            >
              <BiArrowBack size={28} />

              <h1 className="font-body text-xl font-bold leading-8.5 text-heading md:text-2xl">
                Edit Profile
              </h1>
            </button>
          </div>

          <div className="mb-12.5 flex justify-center">
            <div className="relative h-26 w-26">
              <Image
                src={profileImage}
                alt="Profile"
                fill
                unoptimized={profileImage.startsWith("blob:")}
                className="rounded-full object-cover"
              />

              <label
                htmlFor="profile-image"
                className="gradient1 absolute -bottom-4 left-1/2 flex h-8 w-8 -translate-x-1/2 cursor-pointer items-center justify-center rounded-full text-white"
              >
                <FiCamera size={16} />
              </label>

              <input
                ref={fileRef}
                id="profile-image"
                type="file"
                accept="image/*"
                className="hidden"
                onChange={handleImageChange}
              />
            </div>
          </div>

          <form onSubmit={handleSubmit} className="space-y-7.5">
            <div className="grid gap-5 md:grid-cols-2">
              <CustomInput
                name="firstName"
                label="First Name*"
                register={register("firstName")}
                error={errors.firstName?.message}
                icon={<FiUser size={18} />}
              />

              <CustomInput
                name="lastName"
                label="Last Name*"
                register={register("lastName")}
                error={errors.lastName?.message}
                icon={<FiUser size={18} />}
              />

              <CustomPhoneInput
                label="Phone Number*"
                name="mobileNumber"
                control={control}
                error={errors.mobileNumber?.number?.message}
                placeholder="Enter Your Phone Number"
              />

              <CustomInput
                name="email"
                label="Email*"
                register={register("email")}
                error={errors.email?.message}
                icon={<FiMail size={18} />}
                className="text-gray-500! cursor-not-allowed"
                rightIcon={
                  <button
                    type="button"
                    onClick={handleEmailChange}
                    className="font-body cursor-pointer text-base font-medium text-link-1 underline"
                  >
                    Change
                  </button>
                }
                readOnly
                disabled
              />
            </div>

            <Button
              type="submit"
              className="w-full"
              buttonClassName="w-full"
              BtnInnerclassName="!w-full !py-4.5"
            >
              Update
            </Button>
          </form>
        </div>
      </div>
    </div>
  );
}
