"use client";

import { FC, useState, useEffect } from "react";
import { Box, Grid, Tooltip } from "@mui/material";
import { DataGridPro, GridColDef } from "@mui/x-data-grid-pro";
import { useAppContext } from "./AppProvider";

interface QueryListSelectorProps {
  title: string;
  keyName: string;
  values: any;
  width: number;
}

export const QueryListSelector: FC<QueryListSelectorProps> = ({
  title,
  keyName,
  values,
  width,
}) => {
  const [selectionModel, setSelectionModel] = useState([] as any[]);
  const {
    colors: { leafcutterLightBlue, pink, leafcutterElectricBlue, warningPink },
    typography: { small },
    query,
    updateQuery,
  } = useAppContext();
  const isExclude = query[keyName]?.queryType === "exclude";
  const columns: GridColDef[] = [
    {
      field: "value",
      renderHeader: () => (
        <Box sx={{ ...small, fontWeight: "bold" }}>{title}</Box>
      ),
      renderCell: ({ value, row }) => (
        <Tooltip title={row.description}>
          <Box sx={{ width: "100%" }}>{value}</Box>
        </Tooltip>
      ),
      editable: false,
      flex: 1,
    },
  ];
  const rows = Object.keys(values).map((k) => ({
    id: k,
    value: values[k].display,
    description: values[k].description,
    category: values[k].category,
  }));

  useEffect(() => {
    setSelectionModel(query[keyName].values);
  }, [query, keyName, setSelectionModel]);

  return (
    <Grid item xs={width}>
      <Box style={{ height: 280, width: "100%" }}>
        <Grid container direction="column" spacing={2}>
          <Grid item>
            <DataGridPro
              sx={{
                height: 260,
                "& .MuiCheckbox-root": {
                  color: isExclude ? warningPink : leafcutterElectricBlue,
                },
                "& .Mui-selected": {
                  backgroundColor: `${
                    isExclude ? pink : leafcutterLightBlue
                  } !important`,
                },
              }}
              rows={rows}
              columns={columns}
              density="compact"
              pageSizeOptions={[100]}
              checkboxSelection
              disableRowSelectionOnClick
              hideFooter
              disableColumnMenu
              scrollbarSize={10}
              onRowSelectionModelChange={(newSelectionModel) => {
                setSelectionModel(newSelectionModel);
                updateQuery({
                  [keyName]: { values: newSelectionModel },
                });
              }}
              rowSelectionModel={selectionModel}
            />
          </Grid>
        </Grid>
      </Box>
    </Grid>
  );
};
