import React, { useState, useMemo } from "react";
import { Select } from "antd";
import { getCountryListMap } from "country-flags-dial-code";
import styled from "styled-components";

const FlagImage = styled.img`
  width: 20px;
  height: 20px;
`;

const OptionContainer = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
`;

const CountryPicker = (props) => {
  const { placeholder = "Select a country", style, onChange, ...rest } = props;
  const countriesMeta = getCountryListMap();
  const countryArray = Object.values(countriesMeta);

  // Create a searchable map for filtering
  const searchableMap = useMemo(() => {
    return countryArray.reduce((acc, country) => {
      acc[country.code] = `${country.country} (${country.dialCode})`.toLowerCase();
      return acc;
    }, {});
  }, [countryArray]);

  const [selectedCountry, setSelectedCountry] = useState(countriesMeta["IN"]);

  const handleChange = (pickedCountry) => {
    const country = countriesMeta[pickedCountry?.value];

    if (!country) return;
    setSelectedCountry(country);
    if (onChange && typeof onChange === "function") onChange(country);
  };

  const handleFilter = (input, option) => {
    const searchValue = searchableMap[option.value];
    return searchValue.includes(input.toLowerCase());
  };

  // Prepare the options for the Select component
  const options = countryArray.map((country) => ({
    label: (
      <OptionContainer>
        <FlagImage src={`data:image/svg+xml;utf8,${encodeURIComponent(country.flag)}`} alt={country.code} />
        <span style={{ paddingTop: 1 }}>
          {country.country} ({country.dialCode})
        </span>
      </OptionContainer>
    ),
    value: country.code,
  }));

  // Custom render method for the selected label
  const renderSelectedItem = (label, option) => {
    const country = countriesMeta[option.value];
    return (
      <OptionContainer>
        <FlagImage src={`data:image/svg+xml;utf8,${encodeURIComponent(country.flag)}`} alt={country.code} />
        {country.code} ({country.dialCode})
      </OptionContainer>
    );
  };

  return (
    <Select
      showSearch
      placeholder={placeholder}
      onChange={handleChange}
      filterOption={handleFilter}
      style={{ minWidth: 220, ...style }}
      value={selectedCountry.code}
      options={options}
      fieldNames={{ label: "label", value: "value" }}
      labelInValue
      tagRender={renderSelectedItem}
      {...rest}
    />
  );
};

export default CountryPicker;
