import React, { useEffect, useState } from 'react';
import PhoneInput from 'react-phone-input-2';
import 'react-phone-input-2/lib/style.css';
import './PhoneInputComponent.scss'; // Import custom styles
import { useDispatch } from 'react-redux';
import { getMasterCountryList } from '@/redux/thunks/Master/master.thunk';
import { AppDispatch } from '@/redux/store';
import { RootState } from '@/redux/slices';
import { useSelector } from 'react-redux';
import { parsePhoneNumberFromString } from 'libphonenumber-js'

const PhoneInputComponent = ({ onChange, selectedCountry, setSelectedCountry, setPhone, phone, setPhoneNumberFormatted }) => {
  const dispatch = useDispatch<AppDispatch>();

  const { countryList } = useSelector((state: RootState) => state.masterActions);

  // Extract array of sortCodes
  const sortCodes = countryList?.data?.map((country: any) => country.sortCode.toLowerCase());

  const handleOnChange = (value: string, country: any, e, formattedValue) => {
    setPhoneNumberFormatted(formattedValue)
    setPhone(value);
    setSelectedCountry(country.countryCode);
    onChange(formattedValue)
  };

  useEffect(() => {
    dispatch(getMasterCountryList({ perPage: -1 }));
  }, [])

  return (
    <div className="phone-input-container relative xxl:h-[50px] w-full">
      <PhoneInput
        country={selectedCountry || 'at'}
        value={phone}
        countryCodeEditable={false}
        onChange={handleOnChange}
        containerClass="custom-phone-input-container h-full"
        inputClass="custom-phone-input !h-full"
        buttonClass="custom-phone-button"
        dropdownClass="custom-dropdown"
        buttonStyle={{ backgroundColor: 'transparent', border: 'none' }}
        inputStyle={{ width: '100%' }}
        onlyCountries={sortCodes}
      />
      <div className="country-code-overlay">{selectedCountry?.toUpperCase()}</div>
    </div>
  );
};

export default PhoneInputComponent;
