import { Autocomplete, Button, TextField } from "@mui/material";
import { useFormik } from "formik";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { provinceGetBuyersService } from "../../services/province-get-buyers";

export const ProvinceAddBuyerAutoAllocation = ({
  dataTable,
  setDataTable,
  setAddedRows,
  poultryIndex,
}) => {
  const dispatch = useDispatch();
  const [selectedCountry, setSelectedCountry] = useState(null);
  const { provinceGetBuyers } = useSelector((state) => state.provinceSlice);
  const formik = useFormik({
    initialValues: {
      num: "",
    },
  });

  useEffect(() => {
    dispatch(provinceGetBuyersService());
  }, []);

  return (
    <Grid contianer width="70%">
      <Autocomplete
        id="country-select"
        options={provinceGetBuyers?.map((item) => {
          return {
            // disabled: item.debt,
            name: item.debt ? `${item.name} (بدهکار)` : item.name,
            obj: item,
          };
        })}
        getOptionLabel={(option) => option.name}
        getOptionDisabled={(option) => option.disabled}
        value={selectedCountry}
        onChange={(event, newValue) => {
          setSelectedCountry(newValue);
        }}
        renderInput={(params) => (
          <TextField {...params} label="انتخاب خریدار" variant="outlined" />
        )}
      />
      <div style={{ marginTop: "10px" }}></div>
      <NumberInput
        allowLeadingZeros
        thousandSeparator=","
        fullWidth
        id="num"
        label="تعداد مرغ"
        variant="outlined"
        value={formik.values.num}
        error={formik.touched.num ? Boolean(formik.errors.num) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.num && Boolean(formik.errors.num)
            ? formik.errors.num
            : null
        }
      />
      <div style={{ marginTop: "10px" }}></div>

      <Button
        variant="contained"
        fullWidth
        onClick={() => {
          setAddedRows((prevState) => {
            return [
              ...prevState,
              {
                kill_house_key: selectedCountry?.obj?.key,
                poultry_request_key: dataTable[poultryIndex].poultryRequestKey,
                quantity: Number(formik.values.num),
              },
            ];
          });
          setDataTable((prevState) => {
            // let edited = Array.from(prevState);
            const edited = deepCopy(prevState);
            edited[poultryIndex].allocations.push({
              allocationKey: null,
              type: selectedCountry?.obj?.killer,
              buyerName: selectedCountry?.name,
              buyerMobile: selectedCountry?.obj?.phone,
              buyerAddress: selectedCountry?.obj?.systemAddress?.city?.name,
              allocationQuantity: Number(formik.values.num),
              allocationPercent: 0,
              KillingPlace: selectedCountry?.obj?.killPlace,
            });

            edited[poultryIndex].allocationsSum = edited[
              poultryIndex
            ].allocations?.reduce((total, item) => {
              return total + item.allocationQuantity;
            }, 0);

            return edited;
          });
          dispatch(CLOSE_MODAL());
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};

function deepCopy(obj) {
  const newObj = Array.isArray(obj) ? [] : {};
  for (const key in obj) {
    if (typeof obj[key] === "object" && obj[key] !== null) {
      newObj[key] = deepCopy(obj[key]);
    } else {
      newObj[key] = obj[key];
    }
  }
  return newObj;
}
