"use client";

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

interface AddTherapistDetailsModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit?: (data: { name: string; email: string; number: string }) => void;
  isLoading?: boolean;
}

export default function AddTherapistDetailsModal({
  isOpen,
  onClose,
  onSubmit,
  isLoading = false,
}: AddTherapistDetailsModalProps) {
  const t = useTranslations("practiceManager");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [number, setNumber] = useState("");

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

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

  const filteredCountries = countrySearchQuery
    ? searchCountries(countrySearchQuery)
    : countryCodes;

  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 handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (onSubmit && !isLoading) {
      onSubmit({ name, email: normalizeEmail(email), number });
    }
  };

  // Reset form when modal closes
  useEffect(() => {
    if (!isOpen) {
      setName("");
      setEmail("");
      setNumber("");
    }
  }, [isOpen]);

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

        {/* Form */}
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Therapists Name */}
          <div className="space-y-2">
            <label className="block text-sm font-medium text-gray-900">
              {t("modals.addTherapist.therapistName")} <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={t("modals.addTherapist.enterTherapistName")}
              required
              className="w-full px-5 py-4 rounded-full border border-gray-200 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent transition"
            />
          </div>

          {/* E-mail */}
          <div className="space-y-2">
            <label className="block text-sm font-medium text-gray-900">
              {t("modals.addTherapist.email")} <span className="text-red-500">*</span>
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder={t("modals.addTherapist.enterTherapistEmail")}
              required
              className="w-full px-5 py-4 rounded-full border border-gray-200 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent transition"
            />
          </div>

          {/* Number with Country Code */}
          <div className="space-y-2">
            <label className="block text-sm font-medium text-gray-900">
              {t("modals.addTherapist.number")} <span className="text-red-500">*</span>
            </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-4 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>

                {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(number)}
                  onChange={handlePhoneChange}
                  placeholder={t("common.phonePlaceholder")}
                  required
                  className="w-full px-5 py-4 rounded-full border border-gray-200 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent transition"
                />
              </div>
            </div>
          </div>

          {/* Divider */}
          <div className="border-t border-gray-200 pt-6 mt-8">
            {/* Submit Button */}
            <div className="flex justify-end">
              <button
                type="submit"
                disabled={isLoading}
                className="px-8 py-3 bg-[#3B9EC9] text-white font-medium 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 flex items-center gap-2"
              >
                {isLoading && (
                  <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                    <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>
                )}
                {isLoading ? t("common.sending") : t("modals.addTherapist.sendInvitation")}
              </button>
            </div>
          </div>
        </form>
      </div>
    </Modal>
  );
}
