"use client";

import Modal from "@/components/Modal";
import { useState, useRef, useEffect } from "react";
import Image from "next/image";
import { useTranslations } from "next-intl";
import {
  useProfileControllerGetProfileV1,
  useProfileControllerUpdateProfileV1,
} from "@/api/admin/admin-profile/admin-profile";
import { normalizeEmail } from "@/lib/email";
import { customInstance } from "@/config/axios";

interface EditProfileModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function EditProfileModal({ isOpen, onClose }: EditProfileModalProps) {
  const t = useTranslations("practitioner");
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    uuid: "",
    is_active: true,
  });
  const [profileImage, setProfileImage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isUploadingPhoto, setIsUploadingPhoto] = useState(false);
  const [success, setSuccess] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const { data: profileData, isLoading, refetch } = useProfileControllerGetProfileV1({
    query: {
      enabled: isOpen,
    },
  });

  const updateProfileMutation = useProfileControllerUpdateProfileV1();

  useEffect(() => {
    // Admin API returns data.profile instead of data.user
    const profile = (profileData as any)?.data?.profile || (profileData as any)?.data?.user;
    if (profile) {
      setFormData({
        name: profile.name || "",
        email: profile.email || "",
        uuid: profile.uuid || "",
        is_active: profile.is_active ?? true,
      });
      if (profile.profile_photo) {
        setProfileImage(profile.profile_photo);
      }
    }
  }, [profileData]);

  useEffect(() => {
    if (isOpen) {
      setSuccess(false);
    }
  }, [isOpen]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      await updateProfileMutation.mutateAsync({
        data: {
          uuid: formData.uuid,
          name: formData.name,
          email: normalizeEmail(formData.email),
          is_active: formData.is_active,
        },
      });
      refetch();
      setSuccess(true);
      setTimeout(() => {
        onClose();
      }, 2000);
    } catch (error) {
      console.error("Error updating profile:", error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setProfileImage(reader.result as string);
      };
      reader.readAsDataURL(file);

      setIsUploadingPhoto(true);
      try {
        const fd = new FormData();
        fd.append("file", file);

        await customInstance({
          url: "/v1/admin-profile-photo",
          method: "POST",
          data: fd,
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });
        refetch();
      } catch (error) {
        console.error("Error uploading profile photo:", error);
        const profile = (profileData as any)?.data?.profile || (profileData as any)?.data?.user;
        if (profile?.profile_photo) {
          setProfileImage(profile.profile_photo);
        } else {
          setProfileImage(null);
        }
      } finally {
        setIsUploadingPhoto(false);
      }
    }
  };

  const handleDeleteImage = () => {
    setProfileImage(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const PersonIcon = () => (
    <svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
    </svg>
  );

  const EmailIcon = () => (
    <svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75" />
    </svg>
  );

  const inputClassName = "w-full pl-12 pr-4 py-3.5 bg-gray-50 border border-gray-200 rounded-full text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 focus:border-[#3B9EC9] transition";

  if (isLoading) {
    return (
      <Modal isOpen={isOpen} onClose={onClose} size="xl">
        <div className="px-2 py-8 flex justify-center items-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
        </div>
      </Modal>
    );
  }

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="xl">
      <div className="px-2">
        <h2 className="text-2xl font-bold text-gray-900 mb-8">{t("modals.editProfile.title")}</h2>

        {success ? (
          <div className="py-8 text-center">
            <div className="w-16 h-16 mx-auto mb-4 bg-green-100 rounded-full flex items-center justify-center">
              <svg className="w-8 h-8 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <p className="text-lg font-medium text-gray-900">{t("modals.editProfile.success")}</p>
          </div>
        ) : (
        <form onSubmit={handleSubmit} className="space-y-5">
          {/* Profile Picture Section */}
          <div className="flex items-center gap-5 mb-8">
            <div className="relative w-24 h-24 rounded-full overflow-hidden border-2 border-[#3B9EC9] flex-shrink-0">
              {profileImage ? (
                <Image
                  src={profileImage}
                  alt="Profile"
                  fill
                  className="object-cover"
                />
              ) : (
                <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                  <svg className="w-12 h-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                  </svg>
                </div>
              )}
              {isUploadingPhoto && (
                <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-white"></div>
                </div>
              )}
            </div>
            <div className="flex flex-col gap-2">
              <input
                type="file"
                ref={fileInputRef}
                onChange={handleImageChange}
                accept="image/*"
                className="hidden"
                disabled={isUploadingPhoto}
              />
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                disabled={isUploadingPhoto}
                className="px-6 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition disabled:opacity-50 cursor-pointer"
              >
                {isUploadingPhoto ? t("modals.editProfile.uploading") : t("modals.editProfile.changePicture")}
              </button>
              <button
                type="button"
                onClick={handleDeleteImage}
                disabled={isUploadingPhoto}
                className="text-sm font-medium text-gray-500 hover:text-gray-700 transition disabled:opacity-50 cursor-pointer"
              >
                {t("modals.editProfile.delete")}
              </button>
            </div>
          </div>

          {/* Name */}
          <div>
            <label className="block text-sm font-semibold text-gray-800 mb-2">
              {t("modals.editProfile.name")}
            </label>
            <div className="relative">
              <div className="absolute inset-y-0 left-4 flex items-center pointer-events-none">
                <PersonIcon />
              </div>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                placeholder={t("modals.editProfile.enterName")}
                className={inputClassName}
              />
            </div>
          </div>

          {/* Email (Read-only) */}
          <div>
            <label className="block text-sm font-semibold text-gray-800 mb-2">
              {t("modals.editProfile.email")}
            </label>
            <div className="relative">
              <div className="absolute inset-y-0 left-4 flex items-center pointer-events-none">
                <EmailIcon />
              </div>
              <input
                type="email"
                value={formData.email}
                disabled
                className={`${inputClassName} bg-gray-100 cursor-not-allowed`}
              />
            </div>
            <p className="text-xs text-gray-500 mt-1">{t("modals.editProfile.emailHint")}</p>
          </div>

          {/* Divider */}
          <div className="border-t border-gray-100 my-6"></div>

          {/* Buttons */}
          <div className="flex justify-end gap-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              disabled={isSubmitting}
              className="px-8 py-3 text-base font-medium text-gray-700 bg-white border border-gray-200 rounded-full hover:bg-gray-50 transition disabled:opacity-50 cursor-pointer"
            >
              {t("modals.editProfile.cancel")}
            </button>
            <button
              type="submit"
              disabled={isSubmitting || isLoading}
              className="px-8 py-3 text-base font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:ring-offset-2 disabled:opacity-50 cursor-pointer"
            >
              {isSubmitting ? t("modals.editProfile.saving") : t("modals.editProfile.save")}
            </button>
          </div>
        </form>
        )}
      </div>
    </Modal>
  );
}
