"use client";

import { ChangeEvent, useEffect, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { FiCamera, FiMail, FiUser } from "react-icons/fi";
import { useRouter } from "next/navigation";

import Button from "../../../../components/ui/Button";
import Input from "../../../../components/ui/CustomInput";
import CustomPhoneInput from "../../../../components/ui/CustomPhoneInput";
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 useUpdateProfilePicture from "../../../../hooks/features/profile/edit-profile/useUpdateProfilePicture";
import { UserImage } from "../../../../components/ui/CustomUserImage";
import ClientWrapper from "../../../../components/ClientWrapper";
import CustomLink from "../../../../components/ui/CustomLink";
import { useModal } from "../../../../lib/modal-system/ModalContext";

export default function EditProfilePage() {
  const profile = useAppSelector((state) => state.user.user);
  const router = useRouter();
  const { openModal } = useModal();

  const { handleEditProfile, loading } = useEditProfile();

  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  const { register, errors, reset, handleSubmit, control } =
    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);
        }
      },
    });

  const { handleUpdateProfilePicture, isPending: updatingProfilePicture } =
    useUpdateProfilePicture();

  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 = (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];

    if (!file) return;

    const preview = URL.createObjectURL(file);

    // Reset the file input so the same file can be selected again
    if (fileRef.current) {
      fileRef.current.value = "";
    }

    // Open the cropper modal
    openModal("IMAGE_CROPPER", {
      image: preview,
      aspectRatio: 1,
      onCropped: handleCroppedImage,
    });
  };

  const handleCroppedImage = async (croppedImageUrl: string) => {
    if (!profile?.uuid) return;

    // Show cropped preview immediately
    setPreviewImage(croppedImageUrl);

    try {
      // Fetch the blob URL to get a File for upload
      const response = await fetch(croppedImageUrl);
      const blob = await response.blob();
      const file = new File([blob], "profile-picture.jpg", {
        type: "image/jpeg",
        lastModified: Date.now(),
      });

      const formData = new FormData();
      formData.append("file", file);

      await handleUpdateProfilePicture({
        userId: profile.uuid,
        formData,
      });

      // Upload succeeded — the Redux store is updated by the hook,
      // so clearing previewImage will reveal the new profilePicture.
      setPreviewImage(null);
      URL.revokeObjectURL(croppedImageUrl);
    } catch (error) {
      setPreviewImage(null);
      URL.revokeObjectURL(croppedImageUrl);
    }
  };

  if (!mounted || !profile) {
    return <EditProfileSkeleton />;
  }

  return (
    <ClientWrapper fallback={<EditProfileSkeleton />}>
      <section className="p-4 md:p-6 pt-6 2xl:pt-10 2xl:p-10">
        <div className="mb-2.5 flex flex-wrap items-center gap-4 text-sm xl:text-lg">
          <CustomLink href="/admin/profile" className="text-heading">
            Profile
          </CustomLink>

          <span className="text-text">/</span>

          <span className="font-semibold text-link-1">Edit</span>
        </div>

        <h1 className="mb-5 text-base lg:text-lg xl:text-xl 2xl:text-28 font-semibold text-heading 2xl:leading-9.5">
          Edit Profile
        </h1>

        <div className="glass-card-v2 max-w-6xl rounded-2xl p-4 xl:p-6">
          <div className="mb-6 grid grid-cols-1 items-start gap-6 sm:mb-10 lg:grid-cols-3">
            <div className="hidden lg:block" />

            <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>

            <div className="flex justify-center lg:justify-end">
              <Button
                type="button"
                variant="white"
                onClick={handleSubmit}
                disabled={loading}
                BtnInnerclassName="!px-4.5 !py-3.5"
                className="w-full sm:w-auto"
                buttonClassName="w-full shadow-none!"
              >
                Save
              </Button>
            </div>
          </div>

          <div className="grid grid-cols-1 gap-5 md:grid-cols-2 lg:gap-5">
            <Input
              label="First Name"
              required
              icon={<FiUser size={18} />}
              register={register("firstName")}
              error={errors.firstName?.message}
            />

            <Input
              label="Last Name"
              required
              icon={<FiUser size={18} />}
              register={register("lastName")}
              error={errors.lastName?.message}
            />

            <CustomPhoneInput
              label="Mobile Number"
              name="mobileNumber"
              control={control}
              error={errors.mobileNumber?.number?.message}
            />

            <Input
              label="Email"
              required
              disabled
              icon={<FiMail size={18} />}
              register={register("email")}
              error={errors.email?.message}
            />
          </div>
        </div>
      </section>
    </ClientWrapper>
  );
}

function EditProfileSkeleton() {
  return (
    <section className="p-4 md:p-6 pt-6 2xl:pt-10 2xl:p-10 animate-pulse">
      {/* Breadcrumb */}
      <div className="mb-2.5 flex items-center gap-3">
        <div className="h-4 w-16 rounded bg-gray-200" />
        <div className="h-4 w-3 rounded bg-gray-200" />
        <div className="h-4 w-10 rounded bg-gray-200" />
      </div>

      {/* Heading */}
      <div className="mb-5 h-8 w-52 rounded bg-gray-200" />

      {/* Card */}
      <div className="glass-card-v2 max-w-6xl rounded-2xl p-4 xl:p-6">
        {/* Top Section */}
        <div className="mb-6 grid grid-cols-1 items-start gap-6 sm:mb-10 lg:grid-cols-3">
          {/* Empty Column */}
          <div className="hidden lg:block" />

          {/* Profile Image */}
          <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>

          {/* Save Button */}
          <div className="flex justify-center lg:justify-end">
            <div className="h-12 w-full rounded-xl bg-gray-200 sm:w-28" />
          </div>
        </div>

        {/* Form */}
        <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
          {Array.from({ length: 4 }).map((_, index) => (
            <div key={index}>
              {/* Label */}
              <div className="mb-2 h-4 w-28 rounded bg-gray-200" />

              {/* Input */}
              <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>
    </section>
  );
}
