"use client";

import Modal from "@/components/Modal";
import { useState, useRef, useEffect, useMemo } from "react";
import { useTranslations } from "next-intl";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { createClientValidationSchema, ClientFormData } from "@/lib/validations/client-validation";
import { ErrorText } from "@/components/ui/ErrorText";
import { useClientsControllerCreateV1 } from "@/api/user/practitioner-clients/practitioner-clients";
import { normalizeEmail, isEmailAlreadyExistsError, isPhoneAlreadyExistsError } from "@/lib/email";
import { toast } from "react-hot-toast";
import { countryCodes, CountryCode, searchCountries } from "@/constants/countryCodes";
import CountryFlagIcon from "@/components/ui/CountryFlagIcon";
import { useQueryClient } from "@tanstack/react-query";

interface AddClientDetailsModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: (clientData?: any) => void;
}

export default function AddClientDetailsModal({
  isOpen,
  onClose,
  onSuccess
}: AddClientDetailsModalProps) {
  const t = useTranslations("practitioner");
  const tAuth = useTranslations("auth");
  const queryClient = useQueryClient();

  const validationSchema = useMemo(() => createClientValidationSchema({
    nameRequired: t("modals.addClient.validation.nameRequired"),
    nameMin: t("modals.addClient.validation.nameMin"),
    nameMax: t("modals.addClient.validation.nameMax"),
    emailRequired: t("modals.addClient.validation.emailRequired"),
    emailInvalid: t("modals.addClient.validation.emailInvalid"),
    phoneRequired: t("modals.addClient.validation.phoneRequired"),
    phoneInvalid: t("modals.addClient.validation.phoneInvalid"),
    ageRequired: t("modals.addClient.validation.ageRequired"),
    ageMin: t("modals.addClient.validation.ageMin"),
    ageMax: t("modals.addClient.validation.ageMax"),
    ageInteger: t("modals.addClient.validation.ageInteger"),
    genderRequired: t("modals.addClient.validation.genderRequired"),
    genderInvalid: t("modals.addClient.validation.genderInvalid"),
  }), [t]);

  // 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 [phoneNumber, setPhoneNumber] = useState("");
  const countryDropdownRef = useRef<HTMLDivElement>(null);

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    setValue,
    setError,
  } = useForm<ClientFormData>({
    resolver: yupResolver(validationSchema) as any,
    mode: "onBlur",
  });

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

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

  // Handle country selection
  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 [successState, setSuccessState] = useState(false);
  const [showEmailNotice, setShowEmailNotice] = useState(false);
  const successDataRef = useRef<any>(null);

  const { mutate: createClient, isPending } = useClientsControllerCreateV1({
    mutation: {
      onSuccess: (data: any) => {
        setShowEmailNotice(!!data?.email_notice);
        successDataRef.current = data?.data || data;
        reset();
        setPhoneNumber("");
        queryClient.invalidateQueries({ queryKey: ["clients"] });
        setSuccessState(true);
        setTimeout(() => {
          setSuccessState(false);
          onClose();
          if (onSuccess) {
            onSuccess(successDataRef.current);
          }
        }, 3000);
      },
      onError: (error: any) => {
        if (isEmailAlreadyExistsError(error)) {
          setError("email", { message: tAuth("emailAlreadyRegistered") });
          return;
        }
        if (isPhoneAlreadyExistsError(error)) {
          setError("phone", { message: tAuth("phoneAlreadyRegistered") });
          return;
        }
        const rawMessage = error?.response?.data?.message;
        const errorMessage = Array.isArray(rawMessage) ? rawMessage[0] : rawMessage || t("modals.addClient.errorMessage");
        toast.error(errorMessage);
      },
    },
  });

  const onSubmit = (data: ClientFormData) => {
    // Map frontend field names to backend field names
    const payload: any = {
      name: data.name,
      email: normalizeEmail(data.email),
      phone: data.phone,
      age: data.age,
      gender: data.gender,
    };

    createClient({ data: payload });
  };

  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}`;
  };

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

  return (
    <Modal isOpen={isOpen} onClose={onClose} size="xl">
      <div className="px-2">
        {successState ? (
          <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>
            <h3 className="text-xl font-semibold text-gray-900 mb-2">{t("modals.addClient.successMessage")}</h3>
            {showEmailNotice && (
              <p className="mt-3 text-xs text-amber-600">
                <strong>{tAuth("note")}</strong> {tAuth("email_notice")}
              </p>
            )}
          </div>
        ) : (
        <>
        <h2 className="text-2xl font-bold text-gray-900 mb-8">{t("modals.addClient.title")}</h2>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
          {/* Patient Name */}
          <div>
            <label className="block text-sm font-semibold text-gray-800 mb-2">
              {t("modals.addClient.clientName")} <span className="text-[#D12E34]">*</span>
            </label>
            <input
              type="text"
              {...register("name")}
              placeholder={t("modals.addClient.enterClientName")}
              className={getInputClassName(!!errors.name)}
              disabled={isPending}
            />
            <ErrorText message={errors.name?.message} />
          </div>

          {/* E-mail */}
          <div>
            <label className="block text-sm font-semibold text-gray-800 mb-2">
              {t("modals.addClient.email")} <span className="text-[#D12E34]">*</span>
            </label>
            <input
              type="email"
              {...register("email")}
              placeholder={t("modals.addClient.enterClientEmail")}
              className={getInputClassName(!!errors.email)}
              disabled={isPending}
            />
            <ErrorText message={errors.email?.message} />
          </div>

          {/* Mobile Number with Country Code */}
          <div>
            <label className="block text-sm font-semibold text-gray-800 mb-2">
              {t("modals.addClient.number")} <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={isPending}
                >
                  <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(phoneNumber)}
                  onChange={handlePhoneChange}
                  placeholder={t("common.phonePlaceholder")}
                  className={getInputClassName(!!errors.phone)}
                  disabled={isPending}
                />
              </div>
            </div>
            <input type="hidden" {...register("phone")} value={phoneNumber} />
            <ErrorText message={errors.phone?.message} />
          </div>

          {/* Age and Gender Row */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-semibold text-gray-800 mb-2">
                {t("modals.addClient.age")} <span className="text-[#D12E34]">*</span>
              </label>
              <input
                type="number"
                {...register("age")}
                placeholder={t("modals.addClient.enterClientAge")}
                className={getInputClassName(!!errors.age)}
                disabled={isPending}
                min={18}
                max={120}
                onKeyDown={(e) => { if (e.key === '-' || e.key === 'e' || e.key === '+') e.preventDefault(); }}
                onInput={(e) => {
                  const input = e.target as HTMLInputElement;
                  if (input.value.length > 3) input.value = input.value.slice(0, 3);
                  const num = parseInt(input.value);
                  if (num > 120) input.value = '120';
                }}
              />
              <ErrorText message={errors.age?.message} />
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-800 mb-2">
                {t("modals.addClient.gender")} <span className="text-[#D12E34]">*</span>
              </label>
              <div className="relative">
                <select
                  {...register("gender")}
                  className={getSelectClassName(!!errors.gender)}
                  disabled={isPending}
                >
                  <option value="">{t("modals.addClient.select")}</option>
                  <option value="Male">{t("modals.addClient.male")}</option>
                  <option value="Female">{t("modals.addClient.female")}</option>
                  <option value="Other">{t("modals.addClient.other")}</option>
                </select>
                <div className="absolute inset-y-0 right-4 flex items-center pointer-events-none">
                  <svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </div>
              </div>
              <ErrorText message={errors.gender?.message} />
            </div>
          </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={isPending}
              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"
            >
              {isPending ? t("modals.addClient.saving") : t("modals.addClient.addClient")}
            </button>
          </div>
        </form>
        </>
        )}
      </div>
    </Modal>
  );
}
