import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import { Autocomplete, Button, TextField } from "@mui/material";
import { useState } from "react";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useDispatch } from "react-redux";
import { cityGetProvinces } from "../../../city/services/CityGetProvinces";
import { useEffect } from "react";
import { cityGetCity } from "../../../city/services/city-get-city";
import {
  auctionFilterByCity,
  auctionFilterByProvince,
} from "../../../../lib/redux/slices/auctionSlice";

export const AuctionFilterRequestZone = () => {
  const [provinceData, setProvinceData] = useState();
  const [cityData, setCityData] = useState();
  const [provinceKey, setProvinceKey] = useState();

  const [selectedProvince, setSelectedProvince] = useState();
  const [selectedCity, setSelectedCity] = useState();

  const [, setCityKey] = useState();
  const [isExistProvince, setIsExistProvince] = useState(true);

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(cityGetProvinces())
      ?.then((r) => {
        if (r?.payload?.data) {
          setProvinceData(r.payload.data);
        }
      })
      .catch((error) => {
        console.error("Error fetching provinces:", error);
      })
      .finally(() => {
        dispatch(LOADING_END());
      });
  }, []);

  useEffect(() => {
    if (provinceKey) {
      dispatch(LOADING_START());
      dispatch(cityGetCity(provinceKey))
        .then((r) => {
          if (r?.payload?.data) {
            setCityData(r.payload.data);
            setIsExistProvince(false);
          }
        })
        .catch((error) => {
          console.error("Error fetching cities:", error);
        })
        .finally(() => {
          dispatch(LOADING_END());
        });
    } else {
      setCityData([]);
      setIsExistProvince(true);
    }
  }, [provinceKey]);

  return (
    <Grid
      container
      p={SPACING.MEDIUM}
      direction="column"
      flex="1"
      height="100%"
      justifyContent="space-between"
      gap={SPACING.SMALL}
    >
      <Grid container direction="column" gap={SPACING.SMALL}>
        <Grid>
          <Autocomplete
            disablePortal
            id="province"
            options={
              provinceData && Array.isArray(provinceData)
                ? provinceData
                    .filter((i) => i?.key && i?.name)
                    .map((i) => ({ id: i.key, label: i.name }))
                : []
            }
            onChange={(e, value) => {
              if (value) {
                setProvinceKey(value.id);
                setSelectedProvince(value.label);
              } else {
                setProvinceKey(undefined);
                setSelectedProvince(undefined);
              }
            }}
            renderInput={(params) => (
              <TextField {...params} label="استان را انتخاب  کنید" />
            )}
          />
        </Grid>

        <Grid>
          <Autocomplete
            disabled={isExistProvince}
            disablePortal
            id="city"
            options={
              cityData && Array.isArray(cityData)
                ? cityData
                    .filter((i) => i?.key && i?.name)
                    .map((i) => ({ id: i.key, label: i.name }))
                : []
            }
            onChange={(e, value) => {
              if (value) {
                setCityKey(value.id);
                setSelectedCity(value.label);
              } else {
                setCityKey(undefined);
                setSelectedCity(undefined);
              }
            }}
            renderInput={(params) => (
              <TextField {...params} label="شهر را انتخاب  کنید" />
            )}
          />
        </Grid>
      </Grid>
      <Grid>
        <Button
          fullWidth
          variant="contained"
          onClick={() => {
            dispatch(auctionFilterByCity(selectedCity));
            dispatch(auctionFilterByProvince(selectedProvince));
            dispatch(DRAWER({ right: false, bottom: false, content: null }));
          }}
        >
          ثبت اطلاعات
        </Button>
      </Grid>
    </Grid>
  );
};
