"use client";

import Modal from "@/components/Modal";
import { useState, useRef, useEffect } from "react";
import { useTranslations } from "next-intl";
import { useProfile, useUpdateProfile } from "@/api/user/user-profile/user-profile";
import { isPhoneAlreadyExistsError } from "@/lib/email";
import { customInstance } from "@/config/axios";
import { countryCodes, CountryCode, searchCountries } from "@/constants/countryCodes";
import CountryFlagIcon from "@/components/ui/CountryFlagIcon";

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

export default function EditProfileModal({ isOpen, onClose }: EditProfileModalProps) {
  const t = useTranslations("practitioner");
  const tAuth = useTranslations("auth");
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    uuid: "",
    is_active: true,
    mobile: "",
    isd_code: "+1",
  });
  const [profileImage, setProfileImage] = useState<string | null>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isUploadingPhoto, setIsUploadingPhoto] = useState(false);
  const [success, setSuccess] = useState(false);
  const [errors, setErrors] = useState({ name: "", phone: "" });
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Country code dropdown state
  const [isCountryDropdownOpen, setIsCountryDropdownOpen] = useState(false);
  const [countrySearchQuery, setCountrySearchQuery] = useState("");
  const [selectedCountry, setSelectedCountry] = useState<CountryCode>(
    countryCodes.find(c => c.dialCode === "+1") || countryCodes[0]
  );
  const countryDropdownRef = useRef<HTMLDivElement>(null);

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

  const updateProfileMutation = useUpdateProfile();

  // Phone number formatting function - formats based on US/Canada pattern (XXX) XXX-XXXX
  const formatPhoneNumber = (phone: string): string => {
    if (!phone) return "";
    const cleaned = phone.replace(/\D/g, "");

    // Format based on length (US/Canada: 10 digits)
    if (cleaned.length === 0) return "";
    if (cleaned.length <= 3) return `(${cleaned}`;
    if (cleaned.length <= 6) return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3)}`;
    return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6, 10)}`;
  };

  // Handle phone input change
  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const input = e.target.value;
    // Remove all non-digit characters
    const digits = input.replace(/\D/g, "");
    // Limit to 10 digits for phone number (without country code)
    const limitedDigits = digits.slice(0, 10);
    setFormData({ ...formData, mobile: limitedDigits });
    if (errors.phone) setErrors({ ...errors, phone: "" });
  };

  // Handle country selection from dropdown
  const handleCountrySelect = (country: CountryCode) => {
    setSelectedCountry(country);
    setFormData({ ...formData, isd_code: country.dialCode });
    setIsCountryDropdownOpen(false);
    setCountrySearchQuery("");
  };

  // Get filtered countries based on search
  const filteredCountries = countrySearchQuery
    ? searchCountries(countrySearchQuery)
    : countryCodes;

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (countryDropdownRef.current && !countryDropdownRef.current.contains(event.target as Node)) {
        setIsCountryDropdownOpen(false);
        setCountrySearchQuery("");
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (profileData?.data?.user) {
      const profile = profileData.data.user as any;
      const isdCode = profile.isd_code || "+1";
      setFormData({
        name: profile.name || "",
        email: profile.email || "",
        uuid: profile.uuid || "",
        is_active: profile.is_active ?? true,
        mobile: profile.mobile || "",
        isd_code: isdCode,
      });
      // Set selected country based on isd_code
      const matchingCountry = countryCodes.find(c => c.dialCode === isdCode);
      if (matchingCountry) {
        setSelectedCountry(matchingCountry);
      }
      // Set profile photo from API if available
      if (profile.profile_photo) {
        setProfileImage(profile.profile_photo);
      }
    }
  }, [profileData]);

  // Reset success state when modal opens
  useEffect(() => {
    if (isOpen) {
      setSuccess(false);
    }
  }, [isOpen]);

  const validateForm = () => {
    const newErrors = { name: "", phone: "" };
    let isValid = true;
    if (!formData.name.trim()) {
      newErrors.name = t("modals.editProfile.validation.nameRequired");
      isValid = false;
    } else if (formData.name.trim().length < 2) {
      newErrors.name = t("modals.editProfile.validation.nameMin");
      isValid = false;
    }
    if (formData.mobile && formData.mobile.replace(/\D/g, "").length < 7) {
      newErrors.phone = t("modals.editProfile.validation.phoneInvalid");
      isValid = false;
    }
    setErrors(newErrors);
    return isValid;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) return;
    setIsSubmitting(true);
    try {
      await updateProfileMutation.mutateAsync({
        data: {
          name: formData.name,
          mobile: formData.mobile,
          isd_code: formData.mobile ? (formData.isd_code || undefined) : undefined,
        },
      });
      refetch();
      setSuccess(true);
      // Auto-close after showing success message
      setTimeout(() => {
        onClose();
      }, 2000);
    } catch (error) {
      if (isPhoneAlreadyExistsError(error)) {
        setErrors({ name: "", phone: tAuth("phoneAlreadyRegistered") });
      } else {
        console.error("Error updating profile:", error);
      }
    } finally {
      setIsSubmitting(false);
    }
  };

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

      // Upload the file to the server
      setIsUploadingPhoto(true);
      try {
        const formData = new FormData();
        formData.append("file", file);

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

  const handleDeleteImage = async () => {
    const previousImage = profileImage;
    setProfileImage(null);
    setSelectedFile(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
    try {
      await customInstance({
        url: "/v1/profile-photo",
        method: "DELETE",
      });
      refetch();
    } catch (error) {
      console.error("Error deleting profile photo:", error);
      setProfileImage(previousImage);
    }
  };

  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 PhoneIcon = () => (
    <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="M2.25 6.75c0 8.284 6.716 15 15 15h2.25a2.25 2.25 0 002.25-2.25v-1.372c0-.516-.351-.966-.852-1.091l-4.423-1.106c-.44-.11-.902.055-1.173.417l-.97 1.293c-.282.376-.769.542-1.21.38a12.035 12.035 0 01-7.143-7.143c-.162-.441.004-.928.38-1.21l1.293-.97c.363-.271.527-.734.417-1.173L6.963 3.102a1.125 1.125 0 00-1.091-.852H4.5A2.25 2.25 0 002.25 4.5v2.25z" />
    </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 State - Show only success message */}
        {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 ? (
                <img
                  src={profileImage}
                  alt="Profile"
                  className="w-full h-full 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 });
                  if (errors.name) setErrors({ ...errors, name: "" });
                }}
                placeholder={t("modals.editProfile.enterName")}
                className={inputClassName}
              />
            </div>
            {errors.name && (
              <p className="text-sm mt-1" style={{ color: '#D12E34' }}>{errors.name}</p>
            )}
          </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>

          {/* Phone Number with Country Code */}
          <div>
            <label className="block text-sm font-semibold text-gray-800 mb-2">
              {t("modals.editProfile.phoneNumber")}
            </label>
            <div className="flex gap-3">
              {/* Country Code Dropdown */}
              <div className="relative w-36 flex-shrink-0" ref={countryDropdownRef}>
                <button
                  type="button"
                  onClick={() => setIsCountryDropdownOpen(!isCountryDropdownOpen)}
                  className="w-full pl-4 pr-3 py-3.5 bg-gray-50 border border-gray-200 rounded-full text-gray-900 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 focus:border-[#3B9EC9] transition flex items-center justify-between cursor-pointer"
                >
                  <span className="flex items-center gap-2 truncate">
                    <CountryFlagIcon code={selectedCountry.code} name={selectedCountry.name} />
                    <span className="text-sm font-medium">{selectedCountry.dialCode}</span>
                  </span>
                  <svg
                    className={`w-4 h-4 text-gray-400 transition-transform ${isCountryDropdownOpen ? "rotate-180" : ""}`}
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
                  </svg>
                </button>

                {/* Dropdown Menu - Opens upward */}
                {isCountryDropdownOpen && (
                  <div className="absolute z-50 bottom-full mb-1 w-72 max-w-[calc(100vw-3rem)] bg-white border border-gray-200 rounded-xl shadow-lg overflow-hidden">
                    {/* Country List - Positioned first for upward opening */}
                    <div className="max-h-48 overflow-y-auto">
                      {filteredCountries.length > 0 ? (
                        filteredCountries.map((country) => (
                          <button
                            key={country.code}
                            type="button"
                            onClick={() => handleCountrySelect(country)}
                            className={`w-full px-3 py-2.5 flex items-center gap-3 hover:bg-gray-50 transition cursor-pointer ${
                              selectedCountry.code === country.code ? "bg-[#3B9EC9]/10" : ""
                            }`}
                          >
                            <CountryFlagIcon code={country.code} name={country.name} />
                            <span className="flex-1 text-left text-sm text-gray-900 truncate">{country.name}</span>
                            <span className="text-sm text-gray-500">{country.dialCode}</span>
                          </button>
                        ))
                      ) : (
                        <div className="px-3 py-4 text-sm text-gray-500 text-center">
                          {t("modals.editProfile.noCountryFound")}
                        </div>
                      )}
                    </div>
                    {/* Search Input - At bottom for upward opening */}
                    <div className="p-2 border-t border-gray-100">
                      <input
                        type="text"
                        value={countrySearchQuery}
                        onChange={(e) => setCountrySearchQuery(e.target.value)}
                        placeholder={t("modals.editProfile.searchCountry")}
                        className="w-full px-3 py-2 text-sm bg-gray-50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 focus:border-[#3B9EC9]"
                        autoFocus
                      />
                    </div>
                  </div>
                )}
              </div>
              {/* Phone Number */}
              <div className="relative flex-1">
                <input
                  type="tel"
                  value={formatPhoneNumber(formData.mobile)}
                  onChange={handlePhoneChange}
                  placeholder={t("common.phonePlaceholder")}
                  className="w-full px-5 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"
                />
              </div>
            </div>
            {errors.phone && (
              <p className="text-sm mt-1" style={{ color: '#D12E34' }}>{errors.phone}</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>
  );
}
