import { Autocomplete, Box, TextField } from "@mui/material";
import React, { useEffect, useState } from "react";
import Telegram from "../../telegram/telegram";

export interface Country {
  default_name: string;
  country_code: string;
  // patterns?: string;
  iso2: string;
}

function CountriesInput(props: {
  onChange: (country: Country | null) => void;
}) {
  let [countriesList, setCountriesList] = useState([] as Country[]);

  useEffect(() => {
    Telegram.call("help.getCountriesList").then((result: any) => {
      console.log("country:", result);
      let resp: Country[] = [];
      result.countries.map((country: any) => {
        resp.push({
          default_name: country.default_name,
          country_code: country.country_codes[0].country_code,
          // patterns:
          //   country.country_codes[0]?.patterns.length > 0
          //     ? country.country_codes[0]?.patterns[0]
          //     : "",
          iso2: country.iso2,
        });
        return true;
      });
      setCountriesList(resp);
    });
  }, []);

  return (
    <Autocomplete
      disablePortal
      autoHighlight
      id="country-select"
      options={countriesList.sort(function (a, b) {
        const nameA = a.default_name.toUpperCase(); // ignore upper and lowercase
        const nameB = b.default_name.toUpperCase(); // ignore upper and lowercase
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }

        // names must be equal
        return 0;
      })}
      sx={{ width: 200 }}
      onChange={(_event, value) => {
        props.onChange(value as Country);
      }}
      getOptionLabel={(option) => option.default_name}
      renderOption={(props, option) => (
        <Box
          component="li"
          sx={{ "& > img": { mr: 2, flexShrink: 0 } }}
          {...props}
        >
          <img
            loading="lazy"
            width="20"
            src={`https://flagcdn.com/w20/${option.iso2.toLowerCase()}.png`}
            srcSet={`https://flagcdn.com/w40/${option.iso2.toLowerCase()}.png 2x`}
            alt=""
          />
          {option.default_name} ({option.iso2}) +{option.country_code}
        </Box>
      )}
      renderInput={(params) => <TextField {...params} label="Country" />}
    />
  );
}

export default CountriesInput;
