"use client";

import { useState, useRef, useEffect } from "react";
import Modal from "@/components/Modal";
import { useTranslations } from "next-intl";
import { toast } from "react-hot-toast";
import { isEmailAlreadyExistsError, isPhoneAlreadyExistsError } from "@/lib/email";
import { countryCodes, CountryCode, searchCountries } from "@/constants/countryCodes";
import CountryFlagIcon from "@/components/ui/CountryFlagIcon";

interface AddTherapistModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

interface FormErrors {
  name?: string;
  email?: string;
  phone?: string;
}

export default function AddTherapistModal({
  isOpen,
  onClose,
  onSuccess
}: AddTherapistModalProps) {
  const t = useTranslations("practitioner");
  const tAuth = useTranslations("auth");
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
  });
  const [errors, setErrors] = useState<FormErrors>({});

  // 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
  const formatPhoneNumber = (phone: string): string => {
    if (!phone) return "";
    const cleaned = phone.replace(/\D/g, "");
    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)}`;
  };

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const input = e.target.value;
    const digits = input.replace(/\D/g, "");
    const limitedDigits = digits.slice(0, 10);
    setFormData({ ...formData, phone: limitedDigits });
  };

  const handleCountrySelect = (country: CountryCode) => {
    setSelectedCountry(country);
    setIsCountryDropdownOpen(false);
    setCountrySearchQuery("");
  };

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

  const validateForm = (): boolean => {
    const newErrors: FormErrors = {};

    if (!formData.name.trim()) {
      newErrors.name = t("modals.addTherapist.nameRequired");
    } else if (formData.name.length < 2) {
      newErrors.name = t("modals.addTherapist.nameMinLength");
    }

    if (!formData.email.trim()) {
      newErrors.email = t("modals.addTherapist.emailRequired");
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = t("modals.addTherapist.emailInvalid");
    }

    if (!formData.phone.trim()) {
      newErrors.phone = t("modals.addTherapist.phoneRequired");
    } else if (!/^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,9}$/.test(formData.phone)) {
      newErrors.phone = t("modals.addTherapist.phoneInvalid");
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

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

    if (!validateForm()) return;

    setIsLoading(true);
    try {
      // TODO: Replace with actual API call when backend is ready.
      // Apply normalizeEmail(formData.email) to the payload before submit.

      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));

      toast.success(t("modals.addTherapist.successMessage"));
      setFormData({ name: "", email: "", phone: "" });
      setErrors({});
      onClose();
      if (onSuccess) {
        onSuccess();
      }
    } catch (error: any) {
      if (isEmailAlreadyExistsError(error)) {
        setErrors({ email: tAuth("emailAlreadyRegistered") });
        return;
      }
      if (isPhoneAlreadyExistsError(error)) {
        setErrors({ phone: tAuth("phoneAlreadyRegistered") });
        return;
      }
      const errorMessage = error?.response?.data?.message || t("modals.addTherapist.errorMessage");
      toast.error(errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  const handleClose = () => {
    setFormData({ name: "", email: "", phone: "" });
    setErrors({});
    onClose();
  };

  const getInputClassName = (hasError: boolean) => {
    const baseClass = "w-full px-5 py-3.5 bg-gray-50 border rounded-full text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 transition";
    const borderClass = hasError ? "border-[#D12E34] focus:border-[#D12E34]" : "border-gray-200 focus:border-[#3B9EC9]";
    return `${baseClass} ${borderClass}`;
  };

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

        <div className="mb-6 p-3 bg-amber-50 border border-amber-200 rounded-lg">
          <p className="text-sm text-amber-800">
            <strong>Coming soon:</strong> This feature is currently in development. Submissions will not be saved.
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-5">
          {/* Therapist Name */}
          <div>
            <label className="block text-sm font-semibold text-gray-800 mb-2">
              {t("modals.addTherapist.name")} <span className="text-[#D12E34]">*</span>
            </label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              placeholder={t("modals.addTherapist.enterName")}
              className={getInputClassName(!!errors.name)}
              disabled={isLoading}
            />
            {errors.name && <p className="text-[#D12E34] text-sm mt-1">{errors.name}</p>}
          </div>

          {/* Email */}
          <div>
            <label className="block text-sm font-semibold text-gray-800 mb-2">
              {t("modals.addTherapist.email")} <span className="text-[#D12E34]">*</span>
            </label>
            <input
              type="email"
              value={formData.email}
              onChange={(e) => setFormData({ ...formData, email: e.target.value })}
              placeholder={t("modals.addTherapist.enterEmail")}
              className={getInputClassName(!!errors.email)}
              disabled={isLoading}
            />
            {errors.email && <p className="text-[#D12E34] text-sm mt-1">{errors.email}</p>}
          </div>

          {/* Phone Number with Country Code */}
          <div>
            <label className="block text-sm font-semibold text-gray-800 mb-2">
              {t("modals.addTherapist.phone")} <span className="text-[#D12E34]">*</span>
            </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"
                  disabled={isLoading}
                >
                  <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>

                {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">
                    <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("common.noCountryFound")}
                        </div>
                      )}
                    </div>
                    <div className="p-2 border-t border-gray-100">
                      <input
                        type="text"
                        value={countrySearchQuery}
                        onChange={(e) => setCountrySearchQuery(e.target.value)}
                        placeholder={t("common.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 Input */}
              <div className="flex-1">
                <input
                  type="tel"
                  value={formatPhoneNumber(formData.phone)}
                  onChange={handlePhoneChange}
                  placeholder={t("common.phonePlaceholder")}
                  className={getInputClassName(!!errors.phone)}
                  disabled={isLoading}
                />
              </div>
            </div>
            {errors.phone && <p className="text-[#D12E34] text-sm mt-1">{errors.phone}</p>}
          </div>

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

          {/* Submit Button */}
          <div className="flex justify-end pt-2">
            <button
              type="submit"
              disabled={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 disabled:cursor-not-allowed cursor-pointer"
            >
              {isLoading ? (
                <span className="flex items-center gap-2">
                  <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                  {t("modals.addTherapist.sending")}
                </span>
              ) : (
                t("modals.addTherapist.sendInvitation")
              )}
            </button>
          </div>
        </form>
      </div>
    </Modal>
  );
}