"use client";

import { ChangeEvent, useEffect, useRef, useState } from "react";
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";
import useUpdateProfilePicture from "../../../../hooks/features/profile/edit-profile/useUpdateProfilePicture";
import { UserImage } from "../../../../components/ui/CustomImage";
import ClientWrapper from "../../../../components/ClientWrapper";
import { FaSpinner } from "react-icons/fa6";

export default function EditProfilePage() {
  const router = useRouter();

  const profile = useAppSelector((state) => state.user.user);

  const { handleEditProfile, loading } = useEditProfile();
  const { handleUpdateProfilePicture, isPending: updatingProfilePicture } =
    useUpdateProfilePicture();
  const { openModal } = useModal();

  const { handleSendEmailToExisting, loading: sendingMail } =
    useSendEmailToExisting();

  const { control, errors, register, handleSubmit, reset } =
    useAppForm<EditProfileSchema>({
      defaultValues: {
        firstName: "",
        lastName: "",
        email: "",
        mobileNumber: {
          dialCode: "",
          number: "",
        },
      },
      schema: editProfileSchema,
      onSubmit: async (data) => {
        try {
          await handleEditProfile(data);
          router.back();
        } catch (error) {
          console.log(error);
        }
      },
    });

  useEffect(() => {
    if (!profile) return;

    reset({
      firstName: profile.firstName ?? "",
      lastName: profile.lastName ?? "",
      email: profile.email ?? "",
      mobileNumber: {
        dialCode: profile.dialCode ?? "",
        number: profile.mobileNumber ?? "",
      },
    });
  }, [profile, reset]);

  const [previewImage, setPreviewImage] = useState<string | null>(null);

  const fileRef = useRef<HTMLInputElement>(null);

  const handleImageChange = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];

    if (!file || !profile?.uuid) return;

    const preview = URL.createObjectURL(file);

    // show preview immediately
    setPreviewImage(preview);

    const formData = new FormData();
    formData.append("file", file);

    try {
      await handleUpdateProfilePicture({
        userId: profile.uuid,
        formData,
      });

      setPreviewImage(null);

      URL.revokeObjectURL(preview);
    } catch (error) {
      setPreviewImage(null);
      URL.revokeObjectURL(preview);
    }
  };

  const handleEmailChange = async () => {
    if (!profile) return;

    try {
      await handleSendEmailToExisting();

      openModal("UPDATE_EMAIL_CONFIRMATION", {
        email: profile.email,
      });
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <ClientWrapper fallback={<EditProfileSkeleton />}>
      <div className="mx-auto max-w-188.5 px-4">
        <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-lg font-bold leading-8.5 text-heading md:text-xl">
                  Edit Profile
                </h1>
              </button>
            </div>

            <div className="mb-12.5 flex justify-center">
              <div className="relative h-26 w-26">
                <UserImage
                  src={previewImage || profile?.profilePicture || ""}
                  alt="Profile"
                  className="h-full w-full 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-x-4 gap-y-3 2xl:gap-5 md:grid-cols-2">
                <CustomInput
                  name="firstName"
                  label="First Name"
                  required
                  register={register("firstName")}
                  error={errors.firstName?.message}
                  icon={<FiUser size={18} />}
                  placeholder="Enter Your First Name"
                />

                <CustomInput
                  name="lastName"
                  label="Last Name"
                  required
                  register={register("lastName")}
                  error={errors.lastName?.message}
                  icon={<FiUser size={18} />}
                  placeholder="Enter Your Last Name"
                />

                <CustomPhoneInput
                  label="Phone Number"
                  required
                  name="mobileNumber"
                  control={control}
                  error={errors.mobileNumber?.number?.message}
                  placeholder="Enter Your Phone Number"
                />

                <CustomInput
                  name="email"
                  label="Email"
                  required
                  register={register("email")}
                  error={errors.email?.message}
                  icon={<FiMail size={18} />}
                  className="text-gray-500! cursor-not-allowed"
                  rightIcon={
                    <button
                      type="button"
                      onClick={handleEmailChange}
                      disabled={sendingMail}
                      className="disabled:cursor-not-allowed font-body cursor-pointer text-sm font-medium text-link-1 underline"
                    >
                      {sendingMail ? (
                        <span>
                          <FaSpinner className="size-5 animate-spin shrink-0" />
                        </span>
                      ) : (
                        "Change"
                      )}
                    </button>
                  }
                  readOnly
                />
              </div>

              <Button
                type="submit"
                loading={loading}
                className="w-full"
                buttonClassName="w-full"
                BtnInnerclassName="!w-full !py-4.5"
              >
                Update Profile
              </Button>
            </form>
          </div>
        </div>
      </div>
    </ClientWrapper>
  );
}

function EditProfileSkeleton() {
  return (
    <div className="mx-auto max-w-188.5 animate-pulse px-4">
      <div className="glass-card-v2 rounded-2xl p-6 md:p-7.5">
        <div className="mb-8 flex items-center gap-4">
          <div className="h-7 w-7 rounded bg-gray-200" />
          <div className="h-7 w-40 rounded bg-gray-200" />
        </div>

        <div className="mb-12.5 flex justify-center">
          <div className="relative">
            <div className="h-26 w-26 rounded-full bg-gray-200" />
            <div className="absolute -bottom-4 left-1/2 h-8 w-8 -translate-x-1/2 rounded-full bg-gray-300" />
          </div>
        </div>

        <div className="space-y-7.5">
          <div className="grid gap-x-4 gap-y-3 2xl:gap-5 md:grid-cols-2">
            {Array.from({ length: 4 }).map((_, index) => (
              <div key={index}>
                <div className="mb-2 h-4 w-28 rounded bg-gray-200" />

                <div className="flex h-13 items-center rounded-xl border border-gray-200 px-4">
                  <div className="mr-3 h-5 w-5 rounded bg-gray-200" />
                  <div className="h-4 w-3/4 rounded bg-gray-200" />
                </div>
              </div>
            ))}
          </div>

          <div className="h-14 w-full rounded-xl bg-gray-200" />
        </div>
      </div>
    </div>
  );
}
