import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Add, Close } from '@mui/icons-material';
import { Box, Button, ListItemIcon, ListItemText, Menu, MenuItem, TextField, styled } from '@mui/material';
import { defaultCountries, parseCountry, FlagEmoji } from 'react-international-phone';
import type { CountryIso2 } from 'react-international-phone';
import { useMemo, useState } from 'react';

type SearchState = {
  active?: string;
  country?: string;
  q?: string;
};

type Props = {
  search?: SearchState | null;
  onFilterChange: (key: keyof SearchState, value: string) => void;
};

const Root = styled(Box)`
  display: flex;
  flex-direction: column;
  gap: 12px;

  @media (min-width: 960px) {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }

  .filters {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
  }

  .filter-trigger {
    display: inline-flex;
    align-items: center;
    border-radius: 24px;
    background-color: ${({ theme }) => theme.palette.grey[100]};
    color: ${({ theme }) => theme.palette.text.secondary};
    padding: 6px 12px;
    font-size: 14px;
    line-height: 20px;
    text-transform: none;
  }

  .filter-trigger span {
    color: ${({ theme }) => theme.palette.primary.main};
    padding-left: 4px;
  }
`;

export default function TaxFilterToolbar({ search = {}, onFilterChange }: Props) {
  const { t } = useLocaleContext();
  const [statusAnchor, setStatusAnchor] = useState<null | HTMLElement>(null);
  const [countryAnchor, setCountryAnchor] = useState<null | HTMLElement>(null);
  const [countrySearch, setCountrySearch] = useState('');

  const statusLabel = useMemo(() => {
    if (!search?.active) return '';
    if (search.active === 'active') return t('common.active');
    if (search.active === 'inactive') return t('common.inactive');
    return '';
  }, [search?.active, t]);

  type ParsedCountry = ReturnType<typeof parseCountry>;

  const countries = useMemo<ParsedCountry[]>(() => {
    const term = countrySearch.trim().toLowerCase();
    if (!term) {
      return defaultCountries.map((country) => parseCountry(country));
    }
    return defaultCountries
      .map((country) => parseCountry(country))
      .filter(
        (country) =>
          country.name.toLowerCase().includes(term) ||
          country.iso2.toLowerCase().includes(term) ||
          `+${country.dialCode}`.includes(term)
      );
  }, [countrySearch]);

  const selectedCountry = useMemo<ParsedCountry | { iso2: CountryIso2; name: string; dialCode: string } | null>(() => {
    if (!search?.country) return null;
    const match = defaultCountries.find((item) => item[1] === search.country);
    if (!match) {
      return {
        iso2: search.country.toLowerCase() as CountryIso2,
        name: search.country.toUpperCase(),
        dialCode: '',
      };
    }
    return parseCountry(match);
  }, [search?.country]);

  const closeCountryMenu = () => {
    setCountrySearch('');
    setCountryAnchor(null);
  };

  return (
    <Root>
      <Box className="filters">
        <Button
          className="filter-trigger"
          variant="text"
          onClick={(event) => setStatusAnchor(event.currentTarget as HTMLElement)}>
          {search?.active ? (
            <Close
              sx={{ fontSize: 18, mr: 1 }}
              onClick={(event) => {
                event.stopPropagation();
                onFilterChange('active', '');
              }}
            />
          ) : (
            <Add sx={{ fontSize: 18, mr: 1 }} />
          )}
          {t('common.status')}
          {statusLabel && <span>{statusLabel}</span>}
        </Button>
        <Menu
          anchorEl={statusAnchor}
          open={Boolean(statusAnchor)}
          onClose={() => setStatusAnchor(null)}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
          transformOrigin={{ vertical: 'top', horizontal: 'left' }}>
          <MenuItem
            onClick={() => {
              onFilterChange('active', 'active');
              setStatusAnchor(null);
            }}>
            {t('common.active')}
          </MenuItem>
          <MenuItem
            onClick={() => {
              onFilterChange('active', 'inactive');
              setStatusAnchor(null);
            }}>
            {t('common.inactive')}
          </MenuItem>
        </Menu>

        <Button
          className="filter-trigger"
          variant="text"
          onClick={(event) => {
            setCountrySearch('');
            setCountryAnchor(event.currentTarget as HTMLElement);
          }}>
          {search?.country ? (
            <Close
              sx={{ fontSize: 18, mr: 1 }}
              onClick={(event) => {
                event.stopPropagation();
                onFilterChange('country', '');
              }}
            />
          ) : (
            <Add sx={{ fontSize: 18, mr: 1 }} />
          )}
          {t('admin.taxRate.country')}
          {selectedCountry && (
            <Box
              sx={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: 0.75,
                ml: 0.5,
                color: 'primary.main',
              }}>
              <FlagEmoji iso2={selectedCountry.iso2 as CountryIso2} style={{ fontSize: 16 }} />
              {selectedCountry.name}
            </Box>
          )}
        </Button>
        <Menu
          anchorEl={countryAnchor}
          open={Boolean(countryAnchor)}
          onClose={() => closeCountryMenu()}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
          transformOrigin={{ vertical: 'top', horizontal: 'left' }}>
          <Box
            sx={{
              p: 2,
              display: 'flex',
              flexDirection: 'column',
              gap: 1.5,
            }}>
            <TextField
              size="small"
              placeholder={t('admin.taxRate.searchCountry')}
              value={countrySearch}
              onChange={(event) => setCountrySearch(event.target.value)}
              autoFocus
            />
            <Box
              sx={{
                maxHeight: 260,
                overflowY: 'auto',
                border: '1px solid',
                borderColor: 'divider',
                borderRadius: 1,
              }}>
              {countries.map((country) => (
                <MenuItem
                  key={country.iso2}
                  selected={country.iso2 === search?.country}
                  onClick={() => {
                    onFilterChange('country', country.iso2);
                    closeCountryMenu();
                  }}>
                  <ListItemIcon sx={{ minWidth: 32, fontSize: 18, color: 'text.secondary' }}>
                    <FlagEmoji iso2={country.iso2 as CountryIso2} />
                  </ListItemIcon>
                  <ListItemText primary={country.name} />
                </MenuItem>
              ))}
              {!countries.length && (
                <Box sx={{ py: 1.5, px: 2, fontSize: 14, color: 'text.secondary' }}>{t('common.noData')}</Box>
              )}
            </Box>
          </Box>
        </Menu>
      </Box>
    </Root>
  );
}
