import { useState, useCallback } from 'react';
// @mui
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Dialog from '@mui/material/Dialog';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import InputAdornment from '@mui/material/InputAdornment';
import ListItemButton, { listItemButtonClasses } from '@mui/material/ListItemButton';
// types
import { Customer } from 'src/schemas';
// components
import Iconify from 'src/components/iconify';
import SearchNotFound from 'src/components/search-not-found';
import { createFullAddress } from 'src/utils/create-full-address';
import { Tenant } from 'src/schemas';

// ----------------------------------------------------------------------

type Props = {
  title?: string;
  tenant?: Tenant;
  list?: Customer[];
  action?: React.ReactNode;
  //
  open: boolean;
  onClose: VoidFunction;
  //
  selected: (selectedId: string) => boolean;
  onSelect: (address: Customer | Tenant | null) => void;
};

export default function AddressListDialog({
  title = 'Address Book',
  tenant,
  list,
  action,
  //
  open,
  onClose,
  //
  selected,
  onSelect,
}: Props) {
  const [searchCompany, setSearchCompany] = useState('');

  const dataFiltered = applyFilter({
    inputData: list || (tenant ? [tenant] : []),
    query: searchCompany,
  });

  const notFound = !dataFiltered.length && !!searchCompany;

  const handleSearchCompany = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchCompany(event.target.value);
  }, []);

  const handleSelectCompany = useCallback(
    (company: Customer | Tenant | null) => {
      onSelect(company);
      setSearchCompany('');
      onClose();
    },
    [onClose, onSelect]
  );

  const renderList = (
    <Stack
      spacing={0.5}
      sx={{
        p: 0.5,
        maxHeight: 80 * 8,
        overflowX: 'hidden',
      }}
    >
      {dataFiltered.map((company) => (
        <Stack
          key={company.id}
          spacing={0.5}
          component={ListItemButton}
          selected={selected(`${company.id}`)}
          onClick={() => handleSelectCompany(company)}
          sx={{
            py: 1,
            px: 1.5,
            borderRadius: 1,
            flexDirection: 'column',
            alignItems: 'flex-start',
            [`&.${listItemButtonClasses.selected}`]: {
              bgcolor: 'action.selected',
              '&:hover': {
                bgcolor: 'action.selected',
              },
            },
          }}
        >
          <Stack direction="row" alignItems="center" spacing={1}>
            <Typography variant="subtitle2">{company.name}</Typography>

            {/* {address.primary && <Label color="info">Default</Label>} */}
            {/* {<Label color="info">Default</Label>} */}
          </Stack>

          {company.name && (
            <Box sx={{ color: 'primary.main', typography: 'caption' }}>{company.email}</Box>
          )}

          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {createFullAddress(company.address)}
          </Typography>

          {company.phoneNumber && (
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {company.phoneNumber}
            </Typography>
          )}
        </Stack>
      ))}
    </Stack>
  );

  return (
    <Dialog fullWidth maxWidth="xs" open={open} onClose={onClose}>
      <Stack
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        sx={{ p: 3, pr: 1.5 }}
      >
        <Typography variant="h6"> {title} </Typography>

        {action && action}
      </Stack>

      <Stack sx={{ p: 2, pt: 0 }}>
        <TextField
          value={searchCompany}
          onChange={handleSearchCompany}
          placeholder="Search..."
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Iconify icon="eva:search-fill" sx={{ color: 'text.disabled' }} />
              </InputAdornment>
            ),
          }}
        />
      </Stack>

      {notFound ? (
        <SearchNotFound query={searchCompany} sx={{ px: 3, pt: 5, pb: 10 }} />
      ) : (
        renderList
      )}
    </Dialog>
  );
}

// ----------------------------------------------------------------------

function applyFilter({ inputData, query }: { inputData: Tenant[] | Customer[]; query: string }) {
  if (query) {
    return inputData.filter(
      (company) =>
        company.name.toLowerCase().indexOf(query.toLowerCase()) !== -1 ||
        createFullAddress(company.address).toLowerCase().indexOf(query.toLowerCase()) !== -1
    );
  }

  return inputData;
}
