"use client";

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

interface ClientData {
  id: number;
  name: string;
  email?: string;
  phone?: string;
  age?: number;
  gender: string;
}

interface EditClientModalProps {
  isOpen: boolean;
  onClose: () => void;
  client: ClientData | null;
  onSuccess?: () => void;
}

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

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

  // Pre-populate form when client data changes
  useEffect(() => {
    if (client && isOpen) {
      setValue("name", client.name);
      setValue("email", client.email || "");
      const rawPhone = (client.phone || "").replace(/\D/g, "");
      setPhoneNumber(rawPhone);
      setValue("phone", rawPhone);
      if (client.age !== undefined) setValue("age", client.age);
      // Map gender case (backend may return lowercase)
      const genderMap: Record<string, string> = {
        male: "Male",
        female: "Female",
        other: "Other",
        Male: "Male",
        Female: "Female",
        Other: "Other",
      };
      setValue("gender", genderMap[client.gender] || client.gender);
      // Set country code from client data if available
      const clientIsdCode = (client as any)?.isd_code;
      if (clientIsdCode) {
        const matchingCountry = countryCodes.find(c => c.dialCode === clientIsdCode);
        if (matchingCountry) setSelectedCountry(matchingCountry);
      }
    }
  }, [client, isOpen, setValue]);

  const { mutate: updateClient, isPending } = useClientsControllerUpdateV1({
    mutation: {
      onSuccess: () => {
        toast.success(t("modals.editClient.successMessage"));
        // Invalidate clients query to refresh the list
        queryClient.invalidateQueries({ queryKey: getClientsControllerFindAllV1QueryKey() });
        reset();
        onClose();
        if (onSuccess) {
          onSuccess();
        }
      },
      onError: (error: any) => {
        if (isEmailAlreadyExistsError(error)) {
          setError("email", { message: tAuth("emailAlreadyRegistered") });
          return;
        }
        if (isPhoneAlreadyExistsError(error)) {
          setError("phone", { message: tAuth("phoneAlreadyRegistered") });
          return;
        }
        const errorMessage = error?.response?.data?.message || t("modals.editClient.errorMessage");
        toast.error(errorMessage);
      },
    },
  });

  const onSubmit = (data: ClientFormData) => {
    if (!client) return;

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

    updateClient({ id: client.id, data: payload });
  };

  const handleClose = () => {
    reset();
    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}`;
  };

  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={handleClose} size="xl">
      <div className="px-2">
        <h2 className="text-2xl font-bold text-gray-900 mb-8">{t("modals.editClient.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")}
            </label>
            <input
              type="email"
              {...register("email")}
              placeholder={t("modals.addClient.enterClientEmail")}
              className={getInputClassName(!!errors.email)}
              disabled={isPending}
            />
            <ErrorText message={errors.email?.message} />
          </div>

          {/* Number with Country Code */}
          <div>
            <label className="block text-sm font-semibold text-gray-800 mb-2">
              {t("modals.addClient.number")}
            </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")}
              </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(); }}
              />
              <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>

          {/* Buttons */}
          <div className="flex justify-end gap-3 pt-2">
            <button
              type="button"
              onClick={handleClose}
              disabled={isPending}
              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 cursor-pointer disabled:opacity-50"
            >
              {t("modals.editClient.cancel")}
            </button>
            <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.editClient.saving") : t("modals.editClient.save")}
            </button>
          </div>
        </form>
      </div>
    </Modal>
  );
}
