/* eslint-disable @typescript-eslint/no-explicit-any */
import { DefaultSetupValues } from "@/Constant/enums";
import { ErrorMessage, useFormikContext } from "formik";
import React, { useState } from "react";
import PhoneInput from "react-phone-number-input";
import { getCountryCallingCode } from "react-phone-number-input/input";
import { getCountries } from "react-phone-number-input/input";
import en from "react-phone-number-input/locale/en.json";
import type { CountryCode } from "libphonenumber-js/core";
import Select from "react-select";
import type { Props as SelectProps } from "react-select";
// import "./PhoneInputCustom.css";
 
interface FormValues {
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
  password: string;
  confirm_password: string;
  user_type: string;
  // Corporate-only fields
  user_type_id: string;
  nationality: string;
  city: string;
  road: string;
  block: string;
  building: string;
  address_line1: string;
  address_line2: string;
  organization_name: string;
  organization_reg_no: string;
  vat_number: string;
  first_name_ar: string;
  last_name_ar: string;
  description: string;
}
 
interface PhoneInputFieldProps {
  fieldName?: string;
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  error?: string;
  className?: string;
  isFormik?: boolean;
  country?: string; // Optional country ISO2 code
  onCountryChange?: (country: string) => void; // Optional handler for country change
}
 
const customLabels = getCountries().reduce(
  (acc, country) => {
    const countryName = en[country];
    const callingCode = getCountryCallingCode(country);
    if (countryName && callingCode) {
      acc[country] = `${countryName} (+${callingCode})`;
    }
    return acc;
  },
  { ...en } as Record<string, string>
);
 
// Add a mapping from country code to flag emoji
const countryFlagEmoji: Record<string, string> = {
  AF: "🇦🇫", AX: "🇦🇽", AL: "🇦🇱", DZ: "🇩🇿", AS: "🇦🇸", AD: "🇦🇩", AO: "🇦🇴", AI: "🇦🇮", AQ: "🇦🇶", AG: "🇦🇬", AR: "🇦🇷", AM: "🇦🇲", AW: "🇦🇼", AU: "🇦🇺", AT: "🇦🇹", AZ: "🇦🇿", BS: "🇧🇸", BH: "🇧🇭", BD: "🇧🇩", BB: "🇧🇧", BY: "🇧🇾", BE: "🇧🇪", BZ: "🇧🇿", BJ: "🇧🇯", BM: "🇧🇲", BT: "🇧🇹", BO: "🇧🇴", BA: "🇧🇦", BW: "🇧🇼", BR: "🇧🇷", IO: "🇮🇴", BN: "🇧🇳", BG: "🇧🇬", BF: "🇧🇫", BI: "🇧🇮", KH: "🇰🇭", CM: "🇨🇲", CA: "🇨🇦", CV: "🇨🇻", KY: "🇰🇾", CF: "🇨🇫", TD: "🇹🇩", CL: "🇨🇱", CN: "🇨🇳", CX: "🇨🇽", CC: "🇨🇨", CO: "🇨🇴", KM: "🇰🇲", CG: "🇨🇬", CD: "🇨🇩", CK: "🇨🇰", CR: "🇨🇷", CI: "🇨🇮", HR: "🇭🇷", CU: "🇨🇺", CY: "🇨🇾", CZ: "🇨🇿", DK: "🇩🇰", DJ: "🇩🇯", DM: "🇩🇲", DO: "🇩🇴", EC: "🇪🇨", EG: "🇪🇬", SV: "🇸🇻", GQ: "🇬🇶", ER: "🇪🇷", EE: "🇪🇪", ET: "🇪🇹", FK: "🇫🇰", FO: "🇫🇴", FJ: "🇫🇯", FI: "🇫🇮", FR: "🇫🇷", GF: "🇬🇫", PF: "🇵🇫", GA: "🇬🇦", GM: "🇬🇲", GE: "🇬🇪", DE: "🇩🇪", GH: "🇬🇭", GI: "🇬🇮", GR: "🇬🇷", GL: "🇬🇱", GD: "🇬🇩", GP: "🇬🇵", GU: "🇬🇺", GT: "🇬🇹", GG: "🇬🇬", GN: "🇬🇳", GW: "🇬🇼", GY: "🇬🇾", HT: "🇭🇹", VA: "🇻🇦", HN: "🇭🇳", HK: "🇭🇰", HU: "🇭🇺", IS: "🇮🇸", IN: "🇮🇳", ID: "🇮🇩", IR: "🇮🇷", IQ: "🇮🇶", IE: "🇮🇪", IM: "🇮🇲", IL: "🇮🇱", IT: "🇮🇹", JM: "🇯🇲", JP: "🇯🇵", JE: "🇯🇪", JO: "🇯🇴", KZ: "🇰🇿", KE: "🇰🇪", KI: "🇰🇮", KP: "🇰🇵", KR: "🇰🇷", KW: "🇰🇼", KG: "🇰🇬", LA: "🇱🇦", LV: "🇱🇻", LB: "🇱🇧", LS: "🇱🇸", LR: "🇱🇷", LY: "🇱🇾", LI: "🇱🇮", LT: "🇱🇹", LU: "🇱🇺", MO: "🇲🇴", MK: "🇲🇰", MG: "🇲🇬", MW: "🇲🇼", MY: "🇲🇾", MV: "🇲🇻", ML: "🇲🇱", MT: "🇲🇹", MH: "🇲🇭", MQ: "🇲🇶", MR: "🇲🇷", MU: "🇲🇺", YT: "🇾🇹", MX: "🇲🇽", FM: "🇫🇲", MD: "🇲🇩", MC: "🇲🇨", MN: "🇲🇳", ME: "🇲🇪", MS: "🇲🇸", MA: "🇲🇦", MZ: "🇲🇿", MM: "🇲🇲", NA: "🇳🇦", NR: "🇳🇷", NP: "🇳🇵", NL: "🇳🇱", NC: "🇳🇨", NZ: "🇳🇿", NI: "🇳🇮", NE: "🇳🇪", NG: "🇳🇬", NU: "🇳🇺", NF: "🇳🇫", MP: "🇲🇵", NO: "🇳🇴", OM: "🇴🇲", PK: "🇵🇰", PW: "🇵🇼", PS: "🇵🇸", PA: "🇵🇦", PG: "🇵🇬", PY: "🇵🇾", PE: "🇵🇪", PH: "🇵🇭", PN: "🇵🇳", PL: "🇵🇱", PT: "🇵🇹", PR: "🇵🇷", QA: "🇶🇦", RO: "🇷🇴", RU: "🇷🇺", RW: "🇷🇼", RE: "🇷🇪", BL: "🇧🇱", SH: "🇸🇭", KN: "🇰🇳", LC: "🇱🇨", MF: "🇲🇫", PM: "🇵🇲", VC: "🇻🇨", WS: "🇼🇸", SM: "🇸🇲", ST: "🇸🇹", SA: "🇸🇦", SN: "🇸🇳", RS: "🇷🇸", SC: "🇸🇨", SL: "🇸🇱", SG: "🇸🇬", SK: "🇸🇰", SI: "🇸🇮", SB: "🇸🇧", SO: "🇸🇴", ZA: "🇿🇦", SS: "🇸🇸", GS: "🇬🇸", ES: "🇪🇸", LK: "🇱🇰", SD: "🇸🇩", SR: "🇸🇷", SJ: "🇸🇯", SZ: "🇸🇿", SE: "🇸🇪", CH: "🇨🇭", SY: "🇸🇾", TW: "🇹🇼", TJ: "🇹🇯", TZ: "🇹🇿", TH: "🇹🇭", TL: "🇹🇱", TG: "🇹🇬", TK: "🇹🇰", TO: "🇹🇴", TT: "🇹🇹", TN: "🇹🇳", TR: "🇹🇷", TM: "🇹🇲", TC: "🇹🇨", TV: "🇹🇻", UG: "🇺🇬", UA: "🇺🇦", AE: "🇦🇪", GB: "🇬🇧", US: "🇺🇸", UY: "🇺🇾", UZ: "🇺🇿", VU: "🇻🇺", VE: "🇻🇪", VN: "🇻🇳", VG: "🇻🇬", VI: "🇻🇮", WF: "🇼🇫", YE: "🇾🇪", ZM: "🇿🇲", ZW: "🇿🇼"
};
 
// 1. Custom country select component
interface CountrySelectOption {
  value: string | undefined;
  label: string;
}
 
interface CustomCountrySelectProps extends Omit<SelectProps<CountrySelectOption, false>, "value" | "onChange" | "options"> {
  value?: string;
  onChange: (value?: string) => void;
  options: CountrySelectOption[];
}
 
const CustomCountrySelect: React.FC<CustomCountrySelectProps> = ({
  value,
  onChange,
  options,
  ...rest
}) => {
  // Find the selected option object
  const selectedOption = options.find(opt => opt.value === value);
 
  // Custom styles for react-select
  const customStyles = {
    container: (provided: any) => ({
      ...provided,
      width: "36px",
      height: "36px",
      minWidth: "36px",
      minHeight: "36px",
    }),
    control: (provided: any) => ({
      ...provided,
      minHeight: "36px",
      height: "36px",
    }),
    indicatorsContainer: (provided: any) => ({
      ...provided,
      height: "36px",
    }),
    valueContainer: (provided: any) => ({
      ...provided,
      height: "36px",
      padding: "0 6px",
    }),
    option: (provided: any, state: any) => ({
      ...provided,
      padding: '4px 8px',
      fontSize: '0.75rem',
      backgroundColor: state.isFocused ? '#f0f0f0' : '#fff',
      color: '#222',
    }),
    menu: (provided: any) => ({
      ...provided,
      width: "100%",
      minWidth: 150,
    }),
  };
 
  // Custom SingleValue component to show only the flag
  const SingleValue = (props: any) => {
    const countryCode = props.data.value;
    return (
      <div style={{ display: "flex", alignItems: "center", height: "100%", fontSize: 28, paddingLeft: 4 }}>
        {countryCode && countryFlagEmoji[countryCode] ? countryFlagEmoji[countryCode] : null}
      </div>
    );
  };
 
  return (
    <div className="my-custom-dropdown">
      <Select
        value={selectedOption}
        onChange={opt => onChange(opt?.value)}
        options={options
          .filter(option => option.value !== undefined) // <-- filter out undefined
          .map(option => ({
            ...option,
            label: `${
              option.value && countryFlagEmoji[option.value]
                ? countryFlagEmoji[option.value] + " "
                : ""
            }${en[option.value as keyof typeof en]} (+${
              option.value ? getCountryCallingCode(option.value as CountryCode) : ""
            })`,
          }))
        }
        styles={customStyles}
        components={{ SingleValue }}
        {...rest}
        // menuIsOpen
      />
    </div>
  );
};
 
const PhoneInputField: React.FC<PhoneInputFieldProps> = ({
  fieldName = "phone",
  value: externalValue,
  onChange: externalOnChange,
  placeholder = "Phone number",
  error,
  className = "",
  isFormik = true,
  country,
  onCountryChange,
}) => {
  const formikContext = useFormikContext<FormValues>();
  const [phoneNumber, setPhoneNumber] = useState(externalValue || "");
 
  // Inline validation: required, min/max digits, only digits
  const validatePhone = (value: string | undefined) => {
    if (!value || value.trim() === "") {
      return "Phone number is required";
    }
    const cleaned = value.replace(/\s+/g, "");
    if (!/^\+?\d+$/.test(cleaned)) {
      return "Phone number must contain only digits";
    }
    const digits = cleaned.replace(/^\+/, "");
    if (digits.length < 8) {
      return "Phone number is too short";
    }
    if (digits.length > 15) {
      return "Phone number is too long";
    }
    return undefined;
  };
 
  const handlePhoneChange = (value: string | undefined) => {
    const newValue = value || "";
    setPhoneNumber(newValue);
 
    if (isFormik && formikContext) {
      formikContext.setFieldValue(fieldName, newValue);
      const error = validatePhone(value);
      formikContext.setFieldError(fieldName, error);
    } else if (externalOnChange) {
      externalOnChange(newValue);
    }
  };
 
  // Handler to adapt PhoneInput's onCountryChange signature to our prop
  const handleCountryChange = (countryCode?: CountryCode) => {
    if (onCountryChange) {
      onCountryChange(countryCode || "");
    }
  };
 
  // Update internal state when external value changes
  React.useEffect(() => {
    if (externalValue !== undefined) {
      setPhoneNumber(externalValue);
    }
  }, [externalValue]);
 
  return (
    <>
      <style>
        {`     
          @media only screen and (min-device-width : 100px) and (max-device-width : 787px) {
            .css-1tca73a-menu { 
              min-width: 315px; 
              left: -10px;
            }
          }
          @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
            .css-1tca73a-menu { 
              min-width: 220px; 
              left: -5px;
            }
          }       
          .css-zpwqj-control { 
            flex-flow: nowrap;
            position: relative;
          }
          .PhoneInput { column-gap: 10px; }
          .css-1xc3v61-indicatorContainer { padding: 3px; }
          .css-1tca73a-menu { z-index: 3; }
          .css-ayffzb { display: block; }
          .css-ayffzb div:first-child { font-size: 18px!important; }
          .css-1pdftus-container { width: auto; }
          .css-19bb58m { display: none; }
        `}
      </style>
      <div className="input-outer-box">
        <div className="input-style no-borders has-icon validate-field mb-0">
          <PhoneInput
            international
            defaultCountry={DefaultSetupValues?.PhoneCode}
            value={phoneNumber}
            onChange={handlePhoneChange}
            labels={customLabels}
            className={`form-control validate-name phone-input-country ${
              error ? "is-invalid" : ""
            } ${className}`}
            placeholder={placeholder}
            countrySelectComponent={CustomCountrySelect}
            {...(country ? { country } : {})}
            {...(onCountryChange ? { onCountryChange: handleCountryChange } : {})}
          />
        </div>
      </div>
      {error && <div className="text-danger px-2 error-box">{error}</div>}
      {isFormik && (
        <ErrorMessage
          name={fieldName}
          component="div"
          className="error-message"
        />
      )}
    </>
  );
};
 
export default PhoneInputField;

// /* eslint-disable @typescript-eslint/no-explicit-any */
// import React, { useEffect, useState } from "react";
// import PhoneInput from "react-phone-input-2";
// import "react-phone-input-2/lib/style.css";
// import { useFormikContext, ErrorMessage } from "formik";
// import type { FormValues } from "@/Constant/types";

// interface PhoneInputFieldProps {
//   fieldName?: string;
//   value?: string;
//   onChange?: (value: string) => void;
//   placeholder?: string;
//   error?: string;
//   className?: string;
//   isFormik?: boolean;
//   country?: string;
//   onCountryChange?: (country: string) => void;
// }

// const PhoneInputField: React.FC<PhoneInputFieldProps> = ({
//   fieldName = "phone",
//   value: externalValue,
//   onChange: externalOnChange,
//   placeholder = "Phone number",
//   error,
//   className = "",
//   isFormik = true,
//   country = "bh", // default country
//   onCountryChange,
// }) => {
//   const formikContext = useFormikContext<FormValues>();
//   const [phoneNumber, setPhoneNumber] = useState(externalValue || "");

//   const validatePhone = (value: string | undefined) => {
//     if (!value || value.trim() === "") {
//       return "Phone number is required";
//     }
//     const digits = value.replace(/\D/g, "");
//     if (digits.length < 8) return "Phone number is too short";
//     if (digits.length > 15) return "Phone number is too long";
//     return undefined;
//   };

//   // eslint-disable-next-line @typescript-eslint/no-unused-vars
//   const handlePhoneChange = (value: string, data: any, event: any, formattedValue: string) => {
//     setPhoneNumber(value);

//     if (onCountryChange) {
//       onCountryChange(data.countryCode); // like "us", "in", etc.
//     }

//     if (isFormik && formikContext) {
//       formikContext.setFieldValue(fieldName, value);
//       const err = validatePhone(value);
//       formikContext.setFieldError(fieldName, err);
//     } else if (externalOnChange) {
//       externalOnChange(value);
//     }
//   };

//   useEffect(() => {
//     if (externalValue !== undefined) {
//       setPhoneNumber(externalValue);
//     }
//   }, [externalValue]);

//   return (
//     <>
//       <div className="input-outer-box">
//         <div className="input-style no-borders has-icon validate-field mb-0">
//           <PhoneInput
//             country={country}
//             value={phoneNumber}
//             onChange={handlePhoneChange}
//             inputProps={{
//               name: fieldName,
//               required: true,
//               className: `form-control ${error ? "is-invalid" : ""} ${className}`,
//               placeholder,
//             }}
//             enableSearch
//             disableSearchIcon={true}
//             countryCodeEditable={false}
//           />
//         </div>
//       </div>

//       {error && <div className="text-danger px-2 error-box">{error}</div>}
//       {isFormik && (
//         <ErrorMessage name={fieldName} component="div" className="error-message" />
//       )}
//     </>
//   );
// };

// export default PhoneInputField;
