import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  Checkbox,
  FormControl,
  FormControlLabel,
  InputLabel,
  ListItemText,
  MenuItem,
  OutlinedInput,
  Radio,
  RadioGroup,
  Select,
  Typography,
} from "@mui/material";
import { useSelector } from "react-redux";
import { useEffect, useState } from "react";
import { format } from "date-fns-jalali";
import { useDispatch } from "react-redux";
import { auctionFilterByDate } from "../../../../lib/redux/slices/auctionSlice";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";

export const AuctionFilterRequestDate = () => {
  const dispatch = useDispatch();

  const ITEM_HEIGHT = 48;
  const ITEM_PADDING_TOP = 8;

  const { auctions } = useSelector((state) => state.auctionSlice || {});
  const [selectedDates, setSelectedDates] = useState([]);
  const [availableDates, setAvailableDates] = useState([]);
  const [value, setValue] = useState("all");

  const handleChangeRadioButton = (event) => {
    setValue(event.target.value);
  };

  const handleChange = (event) => {
    const {
      target: { value },
    } = event;
    setSelectedDates(
      // On autofill we get a stringified value.
      typeof value === "string" ? value.split(",") : value
    );
  };

  const MenuProps = {
    PaperProps: {
      style: {
        maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
        width: 250,
      },
    },
  };

  useEffect(() => {
    if (auctions && Array.isArray(auctions)) {
      const data = auctions
        .filter((item) => item?.sendDate)
        .map((item) => {
          try {
            return format(new Date(item.sendDate), "yyyy/MM/dd");
          } catch (error) {
            console.error("Error formatting date:", error);
            return null;
          }
        })
        .filter((date) => date !== null);
      setAvailableDates(data);
    } else {
      setAvailableDates([]);
    }
  }, [auctions]);

  return (
    <Grid
      container
      p={SPACING.MEDIUM}
      gap={SPACING.SMALL}
      direction="column"
      flex="1"
      height="100%"
      justifyContent="space-between"
    >
      <Grid container direction="column" gap={SPACING.SMALL}>
        <Grid>
          <FormControl>
            <RadioGroup
              aria-labelledby="demo-controlled-radio-buttons-group"
              name="controlled-radio-buttons-group"
              value={value}
              onChange={handleChangeRadioButton}
            >
              <FormControlLabel
                value="all"
                control={<Radio />}
                label="بدون فیلتر"
              />
              <FormControlLabel
                value="filter"
                control={<Radio />}
                label="انتخاب تاریخ"
              />
            </RadioGroup>
          </FormControl>
        </Grid>
        {value === "filter" && (
          <>
            <Grid>
              <Typography variant="body2">
                تاریخ هایی که مایل به رویت مناقصات آنها هستید را انتخاب کنید.
              </Typography>
            </Grid>
            <Grid>
              <FormControl sx={{ width: "100%" }}>
                <InputLabel id="demo-multiple-checkbox-label">
                  تاریخ های انتخاب شده
                </InputLabel>
                <Select
                  multiple
                  labelId="demo-multiple-checkbox-label"
                  id="demo-multiple-checkbox"
                  value={selectedDates}
                  onChange={handleChange}
                  input={<OutlinedInput label="تاریخ های انتخاب شده" />}
                  renderValue={(selected) =>
                    Array.isArray(selected) ? selected.join(", ") : ""
                  }
                  MenuProps={MenuProps}
                >
                  {availableDates.map((date, i) => (
                    <MenuItem key={(date || "") + i} value={date || ""}>
                      <Checkbox
                        checked={
                          Array.isArray(selectedDates) &&
                          selectedDates.indexOf(date) > -1
                        }
                      />
                      <ListItemText primary={date || ""} />
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
          </>
        )}

        <Grid>
          <Button
            fullWidth
            variant="contained"
            onClick={() => {
              if (value === "all") {
                dispatch(auctionFilterByDate(null));
              } else {
                dispatch(
                  auctionFilterByDate(
                    Array.isArray(selectedDates) ? selectedDates : []
                  )
                );
              }
              dispatch(DRAWER({ right: false, bottom: false, content: null }));
            }}
          >
            ثبت اطلاعات
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );
};
