"use client";

import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { toast } from "sonner";
import SuccessModal from "../common/SuccessModal";
import ChangePasswordModal from "./ChangePasswordModal";
import { useAppDispatch, useAppSelector } from "@/state/hooks";
import { fetchProfile, updateProfile } from "@/state/profile/profileSlice";
import { getImageUrl } from "@/lib/imageUrl";
import AvatarImage from "../common/AvatarImage";

const emptySubscribe = () => () => {};
function useIsMounted() {
  return useSyncExternalStore(
    emptySubscribe,
    () => true,
    () => false
  );
}

function initialsFor(name: string): string {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  const letters = parts.slice(0, 2).map((part) => part[0]?.toUpperCase() ?? "");
  return letters.join("") || "AU";
}

export default function ProfileView() {
  const dispatch = useAppDispatch();
  const mounted = useIsMounted();
  const authUser = useAppSelector((state) => state.auth.user);
  const { profile, loading, saving } = useAppSelector((state) => state.profile);

  const currentUser = mounted ? (profile || authUser) : null;

  const [fullName, setFullName] = useState("");
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [passwordOpen, setPasswordOpen] = useState(false);
  const [successModal, setSuccessModal] = useState<{ title: string; lines: string[] } | null>(null);
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    dispatch(fetchProfile());
  }, [dispatch]);

  // Sync inputs when currentUser updates
  useEffect(() => {
    if (currentUser) {
      const name =
        currentUser.name ||
        (currentUser.firstName
          ? `${currentUser.firstName} ${currentUser.lastName || ""}`.trim()
          : "") ||
        "";
      setFullName(name);
    }
  }, [currentUser]);

  const rawAvatar = avatarPreview || currentUser?.profileImage || currentUser?.avatar || null;
  const currentAvatar = mounted && rawAvatar ? getImageUrl(rawAvatar) : null;

  const displayFullName = mounted ? fullName : "";
  const displayEmail = mounted ? currentUser?.email || "" : "";

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith("image/")) {
      toast.error("Please upload an image file (JPEG or PNG)");
      return;
    }

    const MAX_SIZE = 2 * 1024 * 1024; // 2MB
    if (file.size > MAX_SIZE) {
      toast.error("Profile image must be less than 2MB");
      return;
    }

    setSelectedFile(file);
    setAvatarPreview(URL.createObjectURL(file));
  };

  const handleUpdateProfile = async () => {
    try {
      const parts = fullName.trim().split(/\s+/);
      const firstName = parts[0] || "";
      const lastName = parts.slice(1).join(" ") || "";

      let payload: any;

      if (selectedFile) {
        const formData = new FormData();
        formData.append("profileImage", selectedFile);
        if (firstName) formData.append("firstName", firstName);
        if (lastName) formData.append("lastName", lastName);
        payload = formData;
      } else {
        payload = {
          firstName,
          lastName,
        };
      }

      const resultAction = await dispatch(updateProfile(payload));

      if (updateProfile.fulfilled.match(resultAction)) {
        setSelectedFile(null);
        setSuccessModal({
          title: "Profile Updated Successfully",
          lines: [
            "Your profile information has been saved.",
            "Changes are now live on your account.",
          ],
        });
        toast.success("Profile updated successfully");
      } else if (updateProfile.rejected.match(resultAction)) {
        toast.error(
          (resultAction.payload as string) || "Failed to update profile"
        );
      }
    } catch (err: any) {
      toast.error(err.message || "An unexpected error occurred");
    }
  };

  return (
    <div className="mx-auto min-w-0 max-w-2xl">
      <div>
        <h1 className="text-[20px] font-bold text-[#101828]">My Profile</h1>
        <p className="mt-1 text-[13px] text-[#667085]">
          Manage your personal information and update your account credentials securely.
        </p>
      </div>

      <hr className="mt-4 border-[#E4E7EC]" />

      <div className="mt-6 flex flex-col gap-5">
        <h2 className="text-[14px] font-semibold text-[#101828]">Personal Information :</h2>

        <div>
          <p className="mb-2 text-[13px] font-medium text-[#344054]">Profile Photo</p>
          <div className="relative inline-block">
            <div className="flex h-24 w-24 items-center justify-center rounded-full border-2 border-dashed border-[#D0D5DD] p-1.5">
              <div className="flex h-full w-full items-center justify-center overflow-hidden rounded-full bg-[#1657D9]">
                <AvatarImage
                  src={currentAvatar}
                  alt={displayFullName}
                  initials={initialsFor(displayFullName)}
                />
              </div>
            </div>
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              aria-label="Upload profile photo"
              className="absolute bottom-0 right-0 flex h-8 w-8 items-center justify-center rounded-full border-2 border-white bg-[#1657D9] text-white transition-colors hover:bg-[#1445B0] cursor-pointer"
            >
              <svg width="16" height="16" viewBox="0 0 20 20" fill="none" aria-hidden="true">
                <path
                  d="M7 4.5 5.6 6H4a1.5 1.5 0 0 0-1.5 1.5v6A1.5 1.5 0 0 0 4 15h12a1.5 1.5 0 0 0 1.5-1.5v-6A1.5 1.5 0 0 0 16 6h-1.6L13 4.5H7Z"
                  stroke="currentColor"
                  strokeWidth="1.3"
                  strokeLinejoin="round"
                />
                <circle cx="10" cy="10" r="2.6" stroke="currentColor" strokeWidth="1.3" />
              </svg>
            </button>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleFileChange}
            />
          </div>
        </div>

        <div>
          <label className="mb-1.5 block text-[13px] font-medium text-[#344054]">Full Name</label>
          <input
            type="text"
            value={displayFullName}
            onChange={(e) => setFullName(e.target.value)}
            disabled={loading}
            suppressHydrationWarning
            className="h-10 w-full rounded-lg border border-[#D0D5DD] px-3 text-[13px] text-[#101828] outline-none focus:border-[#1657D9]"
          />
        </div>

        <div>
          <label className="mb-1.5 block text-[13px] font-medium text-[#344054]">Email</label>
          <input
            type="email"
            value={displayEmail}
            disabled
            suppressHydrationWarning
            className="h-10 w-full rounded-lg border border-[#E4E7EC] bg-[#F5F7F9] px-3 text-[13px] text-[#667085] outline-none"
          />
        </div>

        <div className="flex justify-end">
          <button
            type="button"
            onClick={handleUpdateProfile}
            disabled={saving || loading}
            className="h-10 rounded-lg bg-[#1657D9] px-5 text-[13px] font-medium text-white transition-colors hover:bg-[#1445B0] disabled:opacity-50 cursor-pointer"
          >
            {saving ? "Updating..." : "Update Profile"}
          </button>
        </div>
      </div>

      <div className="">
        <h2 className="text-[14px] font-semibold text-[#101828]">Account Security :</h2>

        <div className="mt-4">
          <h3 className="text-[13px] font-semibold text-[#101828]">Change Password</h3>
          <p className="mt-1 text-[13px] text-[#667085]">
            Change your password to keep your account secure. Make sure it&apos;s strong and unique.
          </p>
          <button
            type="button"
            onClick={() => setPasswordOpen(true)}
            className="mt-3 h-9 rounded-lg border border-[#D0D5DD] bg-white px-4 text-[13px] font-medium text-[#1657D9] transition-colors hover:bg-[#F5F7F9] cursor-pointer"
          >
            Change Password
          </button>
        </div>
      </div>

      <ChangePasswordModal
        open={passwordOpen}
        onClose={() => setPasswordOpen(false)}
        onSuccess={() =>
          setSuccessModal({
            title: "Password Updated Successfully",
            lines: ["Your password has been changed.", "Use your new password next time you sign in."],
          })
        }
      />

      <SuccessModal
        open={successModal !== null}
        onClose={() => setSuccessModal(null)}
        title={successModal?.title ?? ""}
        lines={successModal?.lines ?? []}
      />
    </div>
  );
}
