import React, { createContext, useContext, useState, useCallback, Dispatch, SetStateAction } from "react";
import {
  Card,
  CardHeader,
  CardContent,
  IconButton,
  Collapse,
  Checkbox,
  Box,
  FormControlLabel,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";

interface CollapsibleCardProps {
  title: string;
  children: React.ReactNode;
  defaultOpen?: boolean;
  showFilter?: boolean;
  filterText?: string;
}
interface CardFilterContextType {
  filter: boolean;
  onFilterChange: (checked: boolean) => void;
  filterText: string;
  setOnFilterChange: (override: () => void) => void;
}

export const CardFilterContext = createContext<CardFilterContextType>({
  filter: false,
  onFilterChange: (checked: boolean) => {},
  filterText: "FilterText",
  setOnFilterChange: () => {}, //Not working yet
});

const CollapsibleCard: React.FC<CollapsibleCardProps> = ({
  title,
  children,
  defaultOpen = true,
  showFilter = false,
  filterText = "Optional Filter",
}) => {

  const [filter, setFilter] = useState(false);
  const [open, setOpen] = useState(defaultOpen);
  const [onFilterChange, setOnFilterChange] = useState<() => void>();

  const handleFilterChange = useCallback((checked : boolean) => {
    if (onFilterChange) {
      onFilterChange();
    }

    setFilter(checked);
    setOpen(true);
  }, [onFilterChange]);

  return (
    <CardFilterContext.Provider value={{
      filter, onFilterChange: handleFilterChange, filterText, setOnFilterChange
      }}>
      <Card>
        <CardHeader
          title={title}
          action={
            <Box display="flex" justifyContent="flex-end" alignItems="center" gap={1}>
              {showFilter && (
                <>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={filter}
                      onChange={(e) => handleFilterChange(e.target.checked)}
                    />
                  }
                  label={filterText} // Use filterText as the label
                  sx={{ marginRight: 2 }} // Optional: Adjust spacing
                />
                </>)}
              <IconButton onClick={() => setOpen((v) => !v)}>
                {open ? <ExpandLessIcon /> : <ExpandMoreIcon />}
              </IconButton>
            </Box>
          }
        />
        <Collapse in={open}>
          <CardContent>{children}</CardContent>
        </Collapse>
      </Card>
    </CardFilterContext.Provider>
  );
};

export default CollapsibleCard;
