import { useCallback } from 'react';

import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import Badge from '@mui/material/Badge';
import Drawer from '@mui/material/Drawer';
import Button from '@mui/material/Button';
import Avatar from '@mui/material/Avatar';
import Divider from '@mui/material/Divider';
import Tooltip from '@mui/material/Tooltip';
import TextField from '@mui/material/TextField';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Autocomplete from '@mui/material/Autocomplete';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import Iconify from '@/shared/components/iconify';
import Scrollbar from '@/shared/components/scrollbar';
import { IManager, ITaskTableFilters, ITaskTableFilterValue } from '@/contexts/types/tasks';
import { TASK_TYPE_OPTIONS } from '@/shared/_mock';

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

type Props = {
  open: boolean;
  onOpen: VoidFunction;
  onClose: VoidFunction;
  filters: ITaskTableFilters;
  onFilters: (name: string, value: ITaskTableFilterValue) => void;
  canReset: boolean;
  onResetFilters: VoidFunction;
  managerOptions: IManager[];
  typeOptions: string[];
  dateError: boolean;
};

export default function TaskFilters({
  open,
  onOpen,
  onClose,
  filters,
  onFilters,
  canReset,
  onResetFilters,
  typeOptions,
  managerOptions,
  dateError,
}: Props) {
  const handleFilterStartDate = useCallback(
    (newValue: Date | null) => {
      onFilters('startDate', newValue);
    },
    [onFilters]
  );

  const handleFilterEndDate = useCallback(
    (newValue: Date | null) => {
      onFilters('endDate', newValue);
    },
    [onFilters]
  );

  const handleFilterType = useCallback(
    (newValue: string[]) => {
      onFilters('type', newValue);
    },
    [onFilters]
  );

  const handleFilterManager = useCallback(
    (newValue: IManager[]) => {
      onFilters('manager', newValue);
    },
    [onFilters]
  );

  const renderHead = (
    <Stack
      direction="row"
      alignItems="center"
      justifyContent="space-between"
      sx={{ py: 2, pr: 1, pl: 2.5 }}
    >
      <Typography variant="h6" sx={{ flexGrow: 1 }}>
        Filters
      </Typography>

      <Tooltip title="Reset">
        <IconButton onClick={onResetFilters}>
          <Badge color="error" variant="dot" invisible={!canReset}>
            <Iconify icon="solar:restart-bold" />
          </Badge>
        </IconButton>
      </Tooltip>

      <IconButton onClick={onClose}>
        <Iconify icon="mingcute:close-line" />
      </IconButton>
    </Stack>
  );

  const renderDateRange = (
    <Stack>
      <Typography variant="subtitle2" sx={{ mb: 1.5 }}>
        Durations
      </Typography>
      <Stack spacing={2.5}>
        <DatePicker label="Start date" value={filters.startDate} onChange={handleFilterStartDate} />

        <DatePicker
          label="End date"
          value={filters.endDate}
          onChange={handleFilterEndDate}
          slotProps={{
            textField: {
              error: dateError,
              helperText: dateError && 'End date must be later than start date',
            },
          }}
        />
      </Stack>
    </Stack>
  );

  const renderType = (
    <Stack>
      <Typography variant="subtitle2" sx={{ mb: 1.5 }}>
        Type
      </Typography>

      <Autocomplete
        multiple
        id="type"
        options={typeOptions}
        getOptionLabel={(option) => option}
        value={filters.type}
        onChange={(event, newValue) => handleFilterType(newValue)}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="outlined"
            label={filters.type.length ? '+ Type of task' : 'Select the Task Type'}
            placeholder="Select"
          />
        )}
        fullWidth
      />
    </Stack>
  );

  const renderManager = (
    <Stack>
      <Typography variant="subtitle2" sx={{ mb: 1.5 }}>
        Manager
      </Typography>

      <Autocomplete
        multiple
        disableCloseOnSelect
        options={managerOptions}
        value={filters.manager}
        onChange={(event, newValue) => handleFilterManager(newValue)}
        getOptionLabel={(option) => option.name}
        renderInput={(params) => <TextField placeholder="Select Manager" {...params} />}
        renderOption={(props, manager) => (
          <li {...props} key={manager.id}>
            <Avatar
              key={manager.id}
              alt={manager.avatarUrl}
              src={manager.avatarUrl}
              sx={{ width: 24, height: 24, flexShrink: 0, mr: 1 }}
            />
            {manager.name}
          </li>
        )}
        renderTags={(selected, getTagProps) =>
          selected.map((manager, index) => (
            <Chip
              {...getTagProps({ index })}
              key={manager.id}
              size="small"
              variant="soft"
              label={manager.name}
              avatar={<Avatar alt={manager.name} src={manager.avatarUrl} />}
            />
          ))
        }
      />
    </Stack>
  );

  return (
    <>
      <Button
        disableRipple
        color="inherit"
        endIcon={
          <Badge color="error" variant="dot" invisible={!canReset}>
            <Iconify icon="ic:round-filter-list" />
          </Badge>
        }
        onClick={onOpen}
      >
        Filters
      </Button>

      <Drawer
        anchor="right"
        open={open}
        onClose={onClose}
        slotProps={{
          backdrop: { invisible: true },
        }}
        PaperProps={{
          sx: { width: 280 },
        }}
      >
        {renderHead}

        <Divider />

        <Scrollbar sx={{ px: 2.5, py: 3 }}>
          <Stack spacing={3}>
            {renderDateRange}

            {renderType}

            {renderManager}
          </Stack>
        </Scrollbar>
      </Drawer>
    </>
  );
}
