"use client";

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

interface UserData {
  uuid: string;
  name: string;
  email: string;
  isd_code?: string | null;
  mobile?: string | null;
  locale?: string;
  profile_photo?: string | null;
  role?: {
    uuid: string | null;
    name: string | null;
  } | null;
}

interface EditProfileModalProps {
  isOpen: boolean;
  onClose: () => void;
  user?: UserData;
  onSuccess?: () => void;
}

export default function EditProfileModal({ isOpen, onClose, user, onSuccess }: EditProfileModalProps) {
  const t = useTranslations("individual.editProfileModal");
  const tAuth = useTranslations("auth");
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    mobile: "",
    isd_code: "+1",
  });
  const [profileImage, setProfileImage] = useState<string | null>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [shouldDeletePhoto, setShouldDeletePhoto] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [errors, setErrors] = useState({
    name: "",
  });
  const [success, setSuccess] = useState(false);
  const [apiError, setApiError] = useState<string | null>(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);

  // 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 });
  };

  // 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);
  }, []);

  // Reset form state when modal opens
  useEffect(() => {
    if (isOpen) {
      setSelectedFile(null);
      setShouldDeletePhoto(false);
      setErrors({ name: "" });
      setSuccess(false);
      setApiError(null);
    }
  }, [isOpen]);

  // Update form data when user data changes (but don't reset success state)
  useEffect(() => {
    if (isOpen && user && !success) {
      const isdCode = user.isd_code || "+1";
      setFormData({
        name: user.name || "",
        email: user.email || "",
        mobile: user.mobile || "",
        isd_code: isdCode,
      });
      // Set selected country based on isd_code
      const matchingCountry = countryCodes.find(c => c.dialCode === isdCode);
      if (matchingCountry) {
        setSelectedCountry(matchingCountry);
      }
      setProfileImage(user.profile_photo || null);
    }
  }, [user, isOpen, success]);

  const deletePhotoMutation = useDeleteProfilePhoto({
    mutation: {
      onSuccess: () => {
        onSuccess?.();
      },
      onError: (error: any) => {
        setApiError(error?.response?.data?.message || t("photoError"));
      },
    },
  });

  const updateProfileMutation = useUpdateProfile({
    mutation: {
      onSuccess: () => {
        onSuccess?.();
        setSuccess(true);
        // Auto-close after showing success message
        setTimeout(() => {
          onClose();
        }, 2000);
      },
      onError: (error: any) => {
        if (isPhoneAlreadyExistsError(error)) {
          setApiError(tAuth("phoneAlreadyRegistered"));
          return;
        }
        setApiError(error?.response?.data?.message || t("error"));
      },
    },
  });

  const uploadPhotoMutation = useUploadProfilePhoto({
    mutation: {
      onSuccess: () => {
        onSuccess?.();
      },
      onError: (error: any) => {
        setApiError(error?.response?.data?.message || t("photoError"));
      },
    },
  });

  const validateForm = () => {
    const newErrors = {
      name: "",
    };

    let isValid = true;

    // Validate name
    if (!formData.name.trim()) {
      newErrors.name = t("validation.nameRequired");
      isValid = false;
    } else if (formData.name.trim().length < 2) {
      newErrors.name = t("validation.nameMinLength");
      isValid = false;
    }

    setErrors(newErrors);
    return isValid;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setApiError(null);

    if (!validateForm()) {
      return;
    }

    // Delete photo if user clicked delete and hasn't selected a new file
    if (shouldDeletePhoto && !selectedFile) {
      try {
        await deletePhotoMutation.mutateAsync();
      } catch {
        // Error is handled in mutation onError
        return;
      }
    }

    // Upload photo if a new file was selected
    if (selectedFile) {
      try {
        await uploadPhotoMutation.mutateAsync({ data: { file: selectedFile } });
      } catch {
        // Error is handled in mutation onError
        return;
      }
    }

    // Update profile data — send "" for mobile to explicitly clear it when empty
    updateProfileMutation.mutate({
      data: {
        name: formData.name,
        mobile: formData.mobile,
        isd_code: formData.mobile ? (formData.isd_code || undefined) : undefined,
      },
    });
  };

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

  const handleDeleteImage = () => {
    setProfileImage(null);
    setSelectedFile(null);
    setShouldDeletePhoto(true);
    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 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";

  const isLoading = updateProfileMutation.isPending || uploadPhotoMutation.isPending || deletePhotoMutation.isPending;

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

        {/* Success State */}
        {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("success")}</p>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-5">
            {/* API Error */}
            {apiError && (
              <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-600 text-sm">
                {apiError}
              </div>
            )}

            {/* 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-[#3B9EC9] flex items-center justify-center">
                    <span className="text-white font-bold text-3xl">
                      {formData.name?.charAt(0)?.toUpperCase() || "U"}
                    </span>
                  </div>
                )}
              </div>
              <div className="flex flex-col gap-2">
                <input
                  type="file"
                  ref={fileInputRef}
                  onChange={handleImageChange}
                  accept="image/*"
                  className="hidden"
                />
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  className="px-6 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
                >
                  {t("changePicture")}
                </button>
                <button
                  type="button"
                  onClick={handleDeleteImage}
                  className="text-sm font-medium text-gray-500 hover:text-gray-700 transition cursor-pointer"
                >
                  {t("delete")}
                </button>
              </div>
            </div>

            {/* Name */}
            <div>
              <label className="block text-sm font-semibold text-gray-800 mb-2">
                {t("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("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("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("emailHint")}</p>
            </div>

            {/* Phone Number with Country Code */}
            <div>
              <label className="block text-sm font-semibold text-gray-800 mb-2">
                {t("number")}
              </label>
              <div className="flex gap-2">
                {/* Country Code Dropdown */}
                <div className="relative w-28 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("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("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="(555) 555-5555"
                    className="w-full px-3 sm: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>
            </div>

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

            {/* Buttons */}
            <div className="flex flex-col sm:flex-row sm:justify-end gap-3 pt-2">
              <button
                type="button"
                onClick={onClose}
                disabled={isLoading}
                className="w-full sm:w-auto 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("cancel")}
              </button>
              <button
                type="submit"
                disabled={isLoading}
                className="w-full sm:w-auto 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"
              >
                {isLoading ? t("saving") : t("save")}
              </button>
            </div>
          </form>
        )}
      </div>
    </Modal>
  );
}
