
import { useState, useEffect, useCallback } from 'react';
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';
import Iconify from '@/shared/components/iconify';
import SearchNotFound from '@/shared/components/search-not-found';
import { IInvoiceClient, IInvoiceManager } from '@/shared/types/invoice';
import { isIInvoiceClient, isIInvoiceManager } from '@/utils/invoice-type';
import { Button, Chip } from '@mui/material';

type Props = {
  title?: string;
  list: (IInvoiceClient | IInvoiceManager)[];
  action?: React.ReactNode;
  open: boolean;
  isLoading?: boolean;
  onClose: VoidFunction;
  selected: IInvoiceClient | IInvoiceManager | null;
  onSelect: (address: IInvoiceClient | IInvoiceManager | null) => void;
};

export default function AddressListDialog({
  title = 'Address Book',
  list,
  action,
  open,
  onClose,
  isLoading,
  selected,
  onSelect,
}: Props) {
  const [searchAddress, setSearchAddress] = useState('');
  const [dataFiltered, setDataFiltered] = useState<(IInvoiceClient | IInvoiceManager)[]>([]);

  useEffect(() => {
    setDataFiltered(applyFilter({ inputData: list, query: searchAddress }));
  }, [list, searchAddress]);

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

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

  const handleSelectAddress = useCallback(
    (address: IInvoiceClient | IInvoiceManager|null) => {
      onSelect(address);
      setSearchAddress('');
      onClose();
    },
    [onClose, onSelect]
  );

  const renderList = (
    <Stack
      spacing={0.5}
      sx={{
        p: 0.5,
        maxHeight: 80 * 8,
        overflowX: 'hidden',
      }}
    >
      
      {dataFiltered.map((address, index) => {
        if (!address) return null;
        const isSelected = selected
          ? isIInvoiceClient(address) && isIInvoiceClient(selected)
            ? address.company === selected.company
            : isIInvoiceManager(address) && isIInvoiceManager(selected)
            ? address.firstName === selected.firstName && address.lastName === selected.lastName
            : false
          : false;

        return (
          <Stack
            key={isIInvoiceClient(address) ? address.company : `${address.firstName} ${address.lastName}`}
            spacing={0.5}
            component={ListItemButton}
            selected={isSelected}
            onClick={() => handleSelectAddress(address)}
            sx={{
              py: 1,
              px: 2,
              borderRadius: 1,
              flexDirection: 'column',
              alignItems: 'flex-start',
            }}
          >
            <Stack direction="row" alignItems="center" spacing={1} width="100%">
              <Typography variant="subtitle1" noWrap sx={{ flexGrow: 1 }}>
                {isIInvoiceClient(address) ? address.company || address.name : `${address.firstName} ${address.lastName}`}
              </Typography>
              {index === 0 && <Chip label="Default" size="small" color="primary" />}
            </Stack>
            <Typography variant="body2" color="text.secondary" noWrap>
              {isIInvoiceClient(address) ? address.emailAddress : address.email}
            </Typography>
            <Typography variant="body2" color="text.secondary" noWrap>
              {isIInvoiceClient(address) 
                ? `${address.street || ''}, ${address.city || ''}, ${address.country || ''}`
                : ''}
            </Typography>
            <Typography variant="body2" color="text.secondary" noWrap>
              {address.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={searchAddress}
          onChange={handleSearchAddress}
          placeholder="Search..."
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Iconify icon="eva:search-fill" sx={{ color: 'text.disabled' }} />
              </InputAdornment>
            ),
          }}
        />
      </Stack>

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

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

function applyFilter({ inputData, query }: { inputData: (IInvoiceClient | IInvoiceManager)[]; query: string }) {
  if (query) {
    return inputData.filter(
      (address) =>
        address &&
        (
          ('city' in address && `${address.city}`.toLowerCase().indexOf(query.toLowerCase()) !== -1) ||
          ('street' in address && `${address.street}`.toLowerCase().indexOf(query.toLowerCase()) !== -1) ||
          ('apartement' in address && `${address.apartement}`.toLowerCase().indexOf(query.toLowerCase()) !== -1) ||
          ('country' in address && `${address.country}`.toLowerCase().indexOf(query.toLowerCase()) !== -1) ||
          ('emailAddress' in address && `${address.emailAddress}`.toLowerCase().indexOf(query.toLowerCase()) !== -1) ||
          ('company' in address && `${address.company}`.toLowerCase().indexOf(query.toLowerCase()) !== -1) ||
          ('firstName' in address && `${address.firstName}`.toLowerCase().indexOf(query.toLowerCase()) !== -1) ||
          ('lastName' in address && `${address.lastName}`.toLowerCase().indexOf(query.toLowerCase()) !== -1) ||
          ('email' in address && `${address.email}`.toLowerCase().indexOf(query.toLowerCase()) !== -1) ||
          ('phoneNumber' in address && `${address.phoneNumber}`.toLowerCase().indexOf(query.toLowerCase()) !== -1)
        )
    );
  }

  return inputData || [];
}
