import React from 'react';
import {
  IconButton,
  Popover,
  Stack,
  TextField,
  MenuItem,
  Button,
  Badge,
  Divider,
  IconButton as MuiIconButton,
} from '@mui/material';
import { FilterList as FilterListIcon, Close as CloseIcon } from '@mui/icons-material';
import { GridFilterModel, GridColDef } from '@mui/x-data-grid-premium';

interface StatusOption {
  value: string;
  label: string;
}

interface Props {
  columns: GridColDef[];
  filterModel: GridFilterModel;
  setFilterModel: (model: GridFilterModel) => void;
  statusOptions?: StatusOption[]; // optional helper for fgStatus
}

export const CustomFilterButton: React.FC<Props> = ({
  columns,
  filterModel,
  setFilterModel,
  statusOptions = [],
}) => {
  const [anchorEl, setAnchorEl] = React.useState<HTMLElement | null>(null);

  const open = Boolean(anchorEl);

  // count active filters (items that have non-empty field and non-empty value)
  const activeCount = (filterModel?.items || []).filter(
    (i) => i && i.field && i.value !== undefined && i.value !== ''
  ).length;

  const handleClick = (e: React.MouseEvent<HTMLElement>) => {
    // if no items exist, create an initial row (like v5)
    if (!filterModel || !filterModel.items || filterModel.items.length === 0) {
      setFilterModel({
        items: [{ field: columns[0]?.field ?? '', operator: 'contains', value: '' }],
      });
    }
    setAnchorEl(e.currentTarget);
  };
  const handleClose = () => setAnchorEl(null);

  const updateFilter = (index: number, key: keyof GridFilterModel['items'][0], value: any) => {
    const items = [...(filterModel?.items || [])];
    items[index] = { ...(items[index] || {}), [key]: value };
    setFilterModel({ items });
  };

  const addFilter = () => {
    setFilterModel({
      items: [
        ...(filterModel?.items || []),
        { field: columns[0]?.field ?? '', operator: 'contains', value: '' },
      ],
    });
  };

  const removeFilter = (index: number) => {
    const items = [...(filterModel?.items || [])].filter((_, i) => i !== index);
    setFilterModel({ items });
  };

  // helper: get colDef for a field
  const getCol = (field?: string) => columns.find((c) => c.field === field);

  return (
    <>
      <Badge badgeContent={activeCount} color="primary" overlap="circular">
        <IconButton
          size="small"
          onClick={handleClick}
          sx={{ color: '#123375' }}
          aria-label="filter"
        >
          <FilterListIcon />
        </IconButton>
      </Badge>

      <Popover
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
        PaperProps={{ sx: { p: 2, minWidth: 540, maxWidth: '95vw' } }}
      >
        <Stack gap={2}>
          {(filterModel?.items || []).map((item, idx) => {
            const colDef = getCol(item.field as string | undefined);

            // valueOptions from column (v5 pattern: singleSelect)
            const valueOptions =
              ((colDef as any)?.valueOptions ?? (colDef as any)?.type === 'singleSelect')
                ? ((colDef as any)?.valueOptions ?? [])
                : [];

            return (
              <Stack
                key={idx}
                direction="row"
                spacing={1}
                alignItems="center"
                sx={{ width: '100%' }}
              >
                {/* Column */}
                <TextField
                  select
                  size="small"
                  label="Column"
                  value={item.field ?? ''}
                  onChange={(e) => updateFilter(idx, 'field', e.target.value)}
                  InputLabelProps={{ shrink: true }}
                  sx={{ minWidth: 180 }}
                >
                  {columns.map((col) => (
                    <MenuItem key={col.field} value={col.field}>
                      {col.headerName ?? col.field}
                    </MenuItem>
                  ))}
                </TextField>

                {/* Operator */}
                <TextField
                  select
                  size="small"
                  label="Operator"
                  value={(item.operator as string) ?? 'contains'}
                  onChange={(e) => updateFilter(idx, 'operator', e.target.value)}
                  InputLabelProps={{ shrink: true }}
                  sx={{ minWidth: 160 }}
                >
                  <MenuItem value="contains">contains</MenuItem>
                  <MenuItem value="equals">equals</MenuItem>
                  <MenuItem value="is">is</MenuItem>
                  <MenuItem value="isNot">is not</MenuItem>
                </TextField>

                {/* Value: dynamic by column */}
                {colDef &&
                (colDef.type === 'singleSelect' || Array.isArray((colDef as any).valueOptions)) ? (
                  <TextField
                    select
                    size="small"
                    label="Value"
                    value={item.value ?? ''}
                    onChange={(e) => updateFilter(idx, 'value', e.target.value)}
                    InputLabelProps={{ shrink: true }}
                    sx={{ flex: 1, minWidth: 160 }}
                  >
                    {/* prefer column.valueOptions; fallback to statusOptions prop if field=fgStatus */}
                    {(
                      (colDef as any).valueOptions ??
                      (colDef.field === 'fgStatus' ? statusOptions.map((s) => s.value) : [])
                    ).map((opt: any) => (
                      <MenuItem key={String(opt)} value={opt}>
                        {/* if you want label for statusOptions, render label */}
                        {colDef.field === 'fgStatus'
                          ? (statusOptions.find((s) => s.value === opt)?.label ?? String(opt))
                          : String(opt)}
                      </MenuItem>
                    ))}
                  </TextField>
                ) : (
                  <TextField
                    size="small"
                    label="Value"
                    placeholder="Filter Value"
                    value={item.value ?? ''}
                    onChange={(e) => updateFilter(idx, 'value', e.target.value)}
                    InputLabelProps={{ shrink: true }}
                    sx={{ flex: 1, minWidth: 160 }}
                  />
                )}

                <MuiIconButton size="small" onClick={() => removeFilter(idx)}>
                  <CloseIcon fontSize="small" />
                </MuiIconButton>
              </Stack>
            );
          })}

          <Divider />

          <Stack direction="row" justifyContent="space-between" alignItems="center">
            <Button size="small" variant="outlined" onClick={addFilter}>
              + Add filter
            </Button>

            <Stack direction="row" spacing={1}>
              <Button
                size="small"
                onClick={() => {
                  setFilterModel({ items: [] });
                  handleClose();
                }}
              >
                Clear
              </Button>

              <Button
                size="small"
                variant="contained"
                onClick={() => {
                  // close only, actual filter already set by setFilterModel calls
                  handleClose();
                }}
              >
                Apply
              </Button>
            </Stack>
          </Stack>
        </Stack>
      </Popover>
    </>
  );
};
