import React, { useContext, useEffect, useState } from "react";
import {
  Grid,
  TextField,
  Button,
  Autocomplete,
  Typography,
  FormControlLabel,
  Checkbox,
} from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { useDispatch } from "react-redux";
import {
  provinceCreateColdHouseService,
  provinceEditColdHouseService,
  provinceGetAllStewardsService,
} from "../../services/province-cold-houses";
import {
  slaughterGetCitiesService,
  slaughterGetProvinceService,
} from "../../../slaughter-house/services/slaughter-get-provinces";
import { AppContext } from "../../../../contexts/AppContext";

export const ProvinceColdHousesListAddColdHouse = ({
  isEdit,
  updateTable,
  item,
  stewardKey,
  killhouseKey,
}) => {
  const dispatch = useDispatch();
  const [stewardsOptions, setStewardsOptions] = useState([]);
  const validationSchema = Yup.object({
    name: Yup.string().required("این فیلد اجباریست!"),
    address: Yup.string().required("این فیلد اجباریست!"),
    steward_key: Yup.string(),
    province: Yup.string()
      .required("این فیلد اجباری است!")
      .typeError("لطفا فیلد را به درستی وارد کنید!"),
    city: Yup.string()
      .required("این فیلد اجباری است!")
      .typeError("لطفا فیلد را به درستی وارد کنید!"),
    active: Yup.boolean(),
    broadcast: Yup.boolean(),
    relocate: Yup.boolean(),
  });

  const [provinceData, setProvinceData] = useState([]);
  const [cityData, setCityData] = useState([]);
  const [openNotif] = useContext(AppContext);

  useEffect(() => {
    if (!isEdit && !stewardKey) {
      dispatch(provinceGetAllStewardsService()).then((r) => {
        setStewardsOptions(r.payload.data);
      });
    }
  }, []);
  const formik = useFormik({
    initialValues: {
      name: isEdit ? item?.name : "",
      address: isEdit ? item?.address : "",
      steward_key: "",
      province: isEdit ? item?.province : "",
      city: isEdit ? item?.city : "",
      active: isEdit ? item?.active : false,
      broadcast: isEdit ? item?.broadcast : false,
      relocate: isEdit ? item?.relocate : false,
    },
    validationSchema,
    onSubmit: (values) => {
      if (isEdit) {
        dispatch(
          provinceEditColdHouseService({
            cold_house_key: item?.key,
            name: values.name,
            province: values.province,
            city: values.city,
            address: values.address,
            active: values.active,
            broadcast: values.broadcast,
            relocate: values.relocate,
          })
        ).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            dispatch(DRAWER({ right: false, bottom: false, content: null }));
            updateTable();
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
          }
        });
      } else {
        let req = {
          steward_key: killhouseKey
            ? null
            : stewardKey
            ? stewardKey
            : values.steward_key,
          kill_house_key: killhouseKey,
          name: values.name,
          province: values.province,
          city: values.city,
          address: values.address,
          active: values.active,
          broadcast: values.broadcast,
          relocate: values.relocate,
        };
        req = Object.fromEntries(
          Object.entries(req).filter(([_, value]) => value !== null)
        );
        dispatch(provinceCreateColdHouseService(req)).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            dispatch(DRAWER({ right: false, bottom: false, content: null }));
            updateTable();
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
          }
        });
      }
    },
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  useEffect(() => {
    dispatch(slaughterGetProvinceService()).then((r) => {
      setProvinceData(r.payload.data);
    });
  }, []);

  useEffect(() => {
    if (formik.values.province) {
      setCityData(
        [],
        dispatch(slaughterGetCitiesService(formik.values.province)).then(
          (r) => {
            setCityData(r.payload.data);
          }
        )
      );
    }
  }, [formik.values.province]);

  return (
    <Grid xs={12} container justifyContent="center" alignItems="center" gap={2}>
      {!isEdit && !stewardKey && (
        <Grid item xs={12}>
          <Autocomplete
            style={{ width: "100%" }}
            options={
              stewardsOptions
                ? stewardsOptions.map((i) => ({
                    id: i.key,
                    label: `${i.fullname} / ${i.mobile} `,
                    item: i,
                  }))
                : []
            }
            value={formik.values.guild}
            onChange={(e, item) => {
              formik.setFieldValue("steward_key", item?.id);
              formik.validateForm();
            }}
            error={formik.touched.guild && Boolean(formik.errors.guild)}
            helperText={formik.touched.guild && formik.errors.guild}
            getOptionLabel={(option) => option.label}
            renderInput={(params) => (
              <TextField {...params} label="انتخاب مباشر" variant="outlined" />
            )}
          />
        </Grid>
      )}
      <Grid item xs={12}>
        <TextField
          fullWidth
          id="name"
          name="name"
          label="نام سردخانه"
          value={formik.values.name}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={formik.touched.name && Boolean(formik.errors.name)}
          helperText={formik.touched.name && formik.errors.name}
        />
      </Grid>

      <Autocomplete
        style={{ width: "100%" }}
        disablePortal
        id="province"
        options={
          provinceData
            ? provinceData.map((i) => ({ id: i.name, label: i.name }))
            : []
        }
        onChange={(e, value) => {
          formik.setFieldValue("province", value ? value.id : "");
          formik.setFieldValue("city", "");
        }}
        renderInput={(params) => (
          <TextField {...params} label="استان را انتخاب کنید" />
        )}
      />
      {isEdit && (
        <Typography variant="caption" color="error">
          استان: {formik.values.province}
        </Typography>
      )}

      <Autocomplete
        minWidth={210}
        style={{ width: "100%" }}
        disabled={!formik.values.province}
        disablePortal
        id="city"
        options={
          cityData ? cityData.map((i) => ({ id: i.name, label: i.name })) : []
        }
        onChange={(e, value) => {
          formik.setFieldValue("city", value ? value.id : "");
        }}
        renderInput={(params) => (
          <TextField {...params} label="شهر را انتخاب کنید" />
        )}
      />

      {isEdit && (
        <Typography variant="caption" color="error">
          شهر: {formik.values.city}
        </Typography>
      )}

      <Grid item xs={12}>
        <TextField
          fullWidth
          id="address"
          name="address"
          label="آدرس"
          value={formik.values.address}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={formik.touched.address && Boolean(formik.errors.address)}
          helperText={formik.touched.address && formik.errors.address}
        />
      </Grid>

      <Grid item xs={12} container direction="column">
        <FormControlLabel
          control={
            <Checkbox
              checked={formik.values.active}
              onChange={formik.handleChange}
              name="active"
            />
          }
          label="فعال"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={formik.values.broadcast}
              onChange={formik.handleChange}
              name="broadcast"
            />
          }
          label="اجازه پخش"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={formik.values.relocate}
              onChange={formik.handleChange}
              name="relocate"
            />
          }
          label="اجازه جابجایی"
        />
      </Grid>

      <Grid item xs={12}>
        <Button
          disabled={
            isEdit
              ? !formik.isValid
              : stewardKey
              ? !formik.isValid
              : !formik.isValid && !formik.values.steward_key
          }
          fullWidth
          type="submit"
          variant="contained"
          color="primary"
          onClick={formik.handleSubmit}
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};
