'use client';
import React, { useEffect, useState } from 'react';

interface CountryCode {
  code: string;
  label: string;
}

const defaultCountries: CountryCode[] = [
  { code: 'US', label: '+1' },
  { code: 'GB', label: '+44' },
  { code: 'CA', label: '+1' },
  { code: 'AU', label: '+61' },
  { code: 'IN', label: '+91' },
  { code: 'ID', label: '+62' },
  { code: 'SG', label: '+65' },
  { code: 'MY', label: '+60' },
  { code: 'PH', label: '+63' },
  { code: 'VN', label: '+84' },
];

interface PhoneInputProps {
  countries?: CountryCode[];
  placeholder?: string;
  id?: string;
  onChange?: (phoneNumber: string) => void;
  selectPosition?: 'start' | 'end'; // New prop for dropdown position
  defaultValue?: string;
  className?: string; // Added className prop
  fixedDialCode?: boolean;
}

const PhoneInput: React.FC<PhoneInputProps> = ({
  countries = defaultCountries,
  placeholder,
  onChange,
  selectPosition = 'start', // Default position is 'start'
  defaultValue,
  className, // Added className
  fixedDialCode = false,
}) => {
  const normalizeLocalNumber = (value: string) => value.replace(/[^\d]/g, '').replace(/^0+/, '');

  const getInitialValues = (defaultValue: string | undefined, countries: CountryCode[]) => {
    if (!defaultValue) {
      const fallbackCountry = fixedDialCode && countries.length > 0 ? countries[0].code : '';
      return { selectedCountry: fallbackCountry, phoneNumber: '', localNumber: '' };
    }
    for (const country of countries) {
      if (defaultValue.startsWith(country.label)) {
        return {
          selectedCountry: country.code,
          phoneNumber: defaultValue,
          localNumber: normalizeLocalNumber(defaultValue.slice(country.label.length)),
        };
      }
    }
    return {
      selectedCountry: fixedDialCode && countries.length > 0 ? countries[0].code : '',
      phoneNumber: defaultValue,
      localNumber: normalizeLocalNumber(defaultValue),
    };
  };

  const initial = getInitialValues(defaultValue, countries);
  const [selectedCountry, setSelectedCountry] = useState<string>(initial.selectedCountry);
  const [phoneNumber, setPhoneNumber] = useState<string>(initial.phoneNumber);
  const [localNumber, setLocalNumber] = useState<string>(initial.localNumber);

  useEffect(() => {
    const nextInitial = getInitialValues(defaultValue, countries);
    setSelectedCountry(nextInitial.selectedCountry);
    setPhoneNumber(nextInitial.phoneNumber);
    setLocalNumber(nextInitial.localNumber);
  }, [defaultValue, countries, fixedDialCode]);

  const countryCodes: Record<string, string> = countries.reduce(
    (acc, { code, label }) => ({ ...acc, [code]: label }),
    {},
  );

  const emitFixedPhoneNumber = (country: string, nextLocalNumber: string) => {
    const dialCode = countryCodes[country] || '';
    const fullPhoneNumber = `${dialCode}${nextLocalNumber}`;
    setPhoneNumber(fullPhoneNumber);
    if (onChange) {
      onChange(fullPhoneNumber);
    }
  };

  const handleCountryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newCountry = e.target.value;
    if (fixedDialCode) {
      setSelectedCountry(newCountry);
      emitFixedPhoneNumber(newCountry, localNumber);
      return;
    }

    const currentPrefix = countryCodes[selectedCountry] || '';
    let newPhoneNumber: string;
    if (phoneNumber.startsWith(currentPrefix)) {
      const rest = phoneNumber.slice(currentPrefix.length);
      newPhoneNumber = countryCodes[newCountry] + rest;
    } else {
      newPhoneNumber = countryCodes[newCountry];
    }
    setSelectedCountry(newCountry);
    setPhoneNumber(newPhoneNumber);
    if (onChange) {
      onChange(newPhoneNumber);
    }
  };

  const handlePhoneNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (fixedDialCode) {
      const nextLocalNumber = normalizeLocalNumber(e.target.value);
      setLocalNumber(nextLocalNumber);
      emitFixedPhoneNumber(selectedCountry, nextLocalNumber);
      return;
    }

    const newPhoneNumber = e.target.value;
    setPhoneNumber(newPhoneNumber);
    if (onChange) {
      onChange(newPhoneNumber);
    }
  };

  return (
    <div className={`relative flex ${className || ''}`}>
      {/* Dropdown position: Start */}
      {selectPosition === 'start' && (
        <div className="absolute">
          <select
            value={selectedCountry}
            onChange={handleCountryChange}
            className="appearance-none bg-none rounded-l-lg border-0 border-r border-gray-200 bg-transparent py-3 pl-3.5 pr-8 leading-tight text-gray-700 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-800 dark:text-gray-400"
          >
            {countries.map((country) => (
              <option
                key={country.code}
                value={country.code}
                className="text-gray-700 dark:bg-gray-900 dark:text-gray-400"
              >
                {country.code}
              </option>
            ))}
          </select>
          <div className="absolute inset-y-0 flex items-center text-gray-700 pointer-events-none bg-none right-3 dark:text-gray-400">
            <svg
              className="stroke-current"
              width="20"
              height="20"
              viewBox="0 0 20 20"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M4.79175 7.396L10.0001 12.6043L15.2084 7.396"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </div>
        </div>
      )}

      {/* Input field */}
      <input
        type="tel"
        value={fixedDialCode ? localNumber : phoneNumber}
        onChange={handlePhoneNumberChange}
        placeholder={placeholder}
        className={`dark:bg-dark-900 h-11 w-full ${
          selectPosition === 'start'
            ? fixedDialCode
              ? 'pl-[120px]'
              : 'pl-[84px]'
            : fixedDialCode
              ? 'pr-[120px]'
              : 'pr-[84px]'
        } rounded-lg border border-gray-300 bg-transparent py-3 px-4 text-sm text-gray-800 shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30 dark:focus:border-brand-800`}
      />

      {fixedDialCode && selectedCountry && (
        <div
          className={`pointer-events-none absolute inset-y-0 flex items-center text-sm font-medium text-gray-500 dark:text-gray-300 ${
            selectPosition === 'start' ? 'left-[76px]' : 'right-[76px]'
          }`}
        >
          {countryCodes[selectedCountry]}
        </div>
      )}

      {/* Dropdown position: End */}
      {selectPosition === 'end' && (
        <div className="absolute right-0">
          <select
            value={selectedCountry}
            onChange={handleCountryChange}
            className="appearance-none bg-none rounded-r-lg border-0 border-l border-gray-200 bg-transparent py-3 pl-3.5 pr-8 leading-tight text-gray-700 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-800 dark:text-gray-400"
          >
            {countries.map((country) => (
              <option
                key={country.code}
                value={country.code}
                className="text-gray-700 dark:bg-gray-900 dark:text-gray-400"
              >
                {country.code}
              </option>
            ))}
          </select>
          <div className="absolute inset-y-0 flex items-center text-gray-700 pointer-events-none right-3 dark:text-gray-400">
            <svg
              className="stroke-current"
              width="20"
              height="20"
              viewBox="0 0 20 20"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M4.79175 7.396L10.0001 12.6043L15.2084 7.396"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </div>
        </div>
      )}
    </div>
  );
};

export default PhoneInput;
