import { useContext, useEffect } from "react";
import { useDispatch } from "react-redux";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import {
  Autocomplete,
  Button,
  TextField,
  FormControl,
  FormHelperText,
} from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { slaughterEditAllocatedCarService } from "../../services/slaughter-edit-allocated-car";
import { useSlaughterHouseCars } from "../../../file/hooks/useSlaughterHouseCars";
import { PropTypes } from "prop-types";

export const SlaughterEditAllocatedCar = ({
  item,
  updateTable,
  poultryRequestKey,
  killHouseKey,
  killRequestKey,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  // Get available cars
  const slaughterHouseCars = useSlaughterHouseCars(
    poultryRequestKey,
    killHouseKey,
    killRequestKey
  );

  const formik = useFormik({
    initialValues: {
      car: null,
      trafficCode: item?.trafficCode || "",
      amount: item?.barAmount || "",
    },
    validationSchema: Yup.object({
      car: Yup.object().nullable(),
      trafficCode: Yup.string(),
      amount: Yup.number().positive("قیمت باید عدد مثبت باشد").nullable(),
    }),
  });

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

  // Set initial car if available
  useEffect(() => {
    if (slaughterHouseCars && item) {
      const currentCar = slaughterHouseCars.find(
        (car) => car.key === item.carKey
      );
      if (currentCar) {
        formik.setFieldValue("car", currentCar);
      }
    }
  }, [slaughterHouseCars, item]);

  const handleSubmit = () => {
    // Check if at least one field has a value
    if (
      !formik.values.car &&
      !formik.values.trafficCode &&
      !formik.values.amount
    ) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "لطفا حداقل یکی از فیلدها را پر کنید",
        severity: "error",
      });
      return;
    }

    // Build request object
    const requestData = {
      key: item?.killHouseRequestKey,
    };

    // If user is updating car or traffic code, send all 3 parameters together
    if (formik.values.car || formik.values.trafficCode) {
      if (formik.values.car?.key && formik.values.car.key !== item?.carKey) {
        requestData.car_key = formik.values.car.key;
      }

      if (
        formik.values.trafficCode &&
        formik.values.trafficCode !== item?.trafficCode
      ) {
        requestData.traffic_code = formik.values.trafficCode;
      }

      if (formik.values.amount && formik.values.amount !== item?.barAmount) {
        requestData.amount = formik.values.amount;
      }
    }
    // If user is updating only amount, send only amount
    else if (formik.values.amount) {
      requestData.amount = formik.values.amount;
    }

    dispatch(slaughterEditAllocatedCarService(requestData)).then((r) => {
      if (r.payload?.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "ویرایش با موفقیت انجام شد",
          severity: "success",
        });
        dispatch(CLOSE_MODAL());
        if (updateTable) updateTable();
      }
    });
  };

  return (
    <Grid
      container
      direction="column"
      gap={SPACING.SMALL}
      sx={{
        width: {
          xs: "300px",
          md: "400px",
        },
        p: 2,
      }}
    >
      <FormControl fullWidth>
        <Autocomplete
          options={slaughterHouseCars || []}
          getOptionLabel={(car) => {
            if (car) {
              const carType = car.type === "exclusive" ? "اختصاصی" : "اجاره ای";
              return `${car.driverName} (${car.driverMobile}) ${car.typeCar} پلاک ${car.pelak} (${carType})`;
            }
            return "";
          }}
          value={formik.values.car}
          onChange={(e, car) => {
            formik.setFieldValue("car", car);
            if (car?.healthCode) {
              formik.setFieldValue("trafficCode", car.healthCode);
            }
          }}
          onBlur={formik.handleBlur}
          renderInput={(params) => (
            <TextField
              {...params}
              label="انتخاب خودرو و راننده (اختیاری)"
              error={formik.touched.car ? Boolean(formik.errors.car) : null}
            />
          )}
        />
        <FormHelperText>
          {formik.touched.car && Boolean(formik.errors.car)
            ? formik.errors.car
            : null}
        </FormHelperText>
      </FormControl>

      <FormControl fullWidth>
        <TextField
          id="trafficCode"
          label="کد حمل و نقل (اختیاری)"
          value={formik.values.trafficCode}
          error={
            formik.touched.trafficCode
              ? Boolean(formik.errors.trafficCode)
              : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.trafficCode && Boolean(formik.errors.trafficCode)
              ? formik.errors.trafficCode
              : null
          }
          variant="outlined"
        />
      </FormControl>

      <FormControl fullWidth>
        <TextField
          id="amount"
          name="amount"
          label="قیمت (اختیاری)"
          type="number"
          value={formik.values.amount}
          error={formik.touched.amount ? Boolean(formik.errors.amount) : null}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.amount && Boolean(formik.errors.amount)
              ? formik.errors.amount
              : null
          }
          variant="outlined"
        />
      </FormControl>

      <Button
        variant="contained"
        color="primary"
        onClick={handleSubmit}
        disabled={
          !formik.values.car &&
          !formik.values.trafficCode &&
          !formik.values.amount
        }
        fullWidth
      >
        ثبت تغییرات
      </Button>
    </Grid>
  );
};

SlaughterEditAllocatedCar.propTypes = {
  item: PropTypes.object.isRequired,
  updateTable: PropTypes.func,
  poultryRequestKey: PropTypes.string,
  killHouseKey: PropTypes.string,
  killRequestKey: PropTypes.string,
};
