import React, { useContext, useEffect, useState } from "react";
import {
  Autocomplete,
  Button,
  Stack,
  TextField,
  Typography,
  Paper,
} from "@mui/material";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch, useSelector } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { slaughterGetPoultriesService } from "../../../slaughter-house/services/salughter-get-poultries";
import { avicultureGetHatchingDataForIncreaseHatching } from "../../../aviculture/services/aviculture-get-hatching-data";
import {
  cityEditIncreaseHatchingeService,
  cityIncreaseHatchingeService,
} from "../../services/city-increase-hatching";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

export const CityIncreaseHatchingSubmitDiffrence = ({
  updateTable,
  isEdit,
  item,
}) => {
  const [poultryData, setPoultryData] = useState([]);
  const [selectedPoultryInfo, setSelectedPoultryInfo] = useState(null);
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const { slaughterGetPoultries } = useSelector(
    (state) => state.slaughterSlice
  );

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

  const initialValues = {
    poultry: item?.poultrykey || null,
    hatching_key: item?.hatchingkey || null,
    quantity: item?.quantity || null,
    message: item?.message || null,
  };

  const validationSchema = Yup.object().shape({
    poultry: Yup.string().required("انتخاب مرغدار الزامی است"),
    hatching_key: Yup.string().required("انتخاب محل پرورش الزامی است"),
    quantity: Yup.number()
      .typeError("عدد وارد کنید")
      .required("حجم الزامی است"),
    message: Yup.string()
      .typeError("پر کردن این فیلد الزامی است")
      .required("پیام الزامی است"),
  });

  const formik = useFormik({
    initialValues,
    validationSchema,
  });

  useEffect(() => {
    if (formik.values.poultry) {
      dispatch(
        avicultureGetHatchingDataForIncreaseHatching(formik.values.poultry, {
          increase: true,
        })
      ).then((res) => {
        setPoultryData(res.payload.data || []);
      });
    }
  }, [formik.values.poultry]);

  return (
    <Stack spacing={2}>
      <Autocomplete
        id="poultry"
        disableClearable
        options={slaughterGetPoultries?.map((item) => ({
          label: `${item.unitName} (${item.user?.fullname})(${item.user?.mobile})`,
          value: item.key,
        }))}
        getOptionLabel={(option) => option.label}
        onChange={(_, value) => {
          formik.setFieldValue("poultry", value.value);
          formik.setFieldValue("hatching_key", null);
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            label="انتخاب مرغدار"
            error={formik.touched.poultry && Boolean(formik.errors.poultry)}
            helperText={formik.touched.poultry && formik.errors.poultry}
          />
        )}
      />

      <Autocomplete
        id="hatching_key"
        disableClearable
        disabled={!formik.values.poultry}
        options={poultryData?.map((item) => ({
          label: item?.poultry?.unitName || "-",
          value: item?.key,
        }))}
        getOptionLabel={(option) => option.label}
        onChange={(_, value) => {
          formik.setFieldValue("hatching_key", value?.value);
          const selected = poultryData.find((i) => i.key === value?.value);
          setSelectedPoultryInfo(selected);
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            label="انتخاب محل پرورش"
            error={
              formik.touched.hatching_key && Boolean(formik.errors.hatching_key)
            }
            helperText={
              formik.touched.hatching_key && formik.errors.hatching_key
            }
          />
        )}
      />

      {selectedPoultryInfo && (
        <Paper variant="outlined" sx={{ p: 2, borderRadius: 2 }}>
          <Typography>
            شماره مجوز جوجه ریزی:{" "}
            {selectedPoultryInfo?.licenceNumber?.toLocaleString()}
          </Typography>
          <Typography>
            شناسه یکتا مرغدار :{" "}
            {selectedPoultryInfo?.poultry?.breedingUniqueId?.toLocaleString()}
          </Typography>
          <Typography>
            حجم جوجه ریزی:
            {selectedPoultryInfo?.quantity?.toLocaleString()}قطعه
          </Typography>

          <Typography>
            سن جوجه: {selectedPoultryInfo?.chickenAge?.toLocaleString()} روز
          </Typography>
          <Typography>
            مانده در سالن: {selectedPoultryInfo?.leftOver?.toLocaleString()}
            قطعه
          </Typography>
          <Typography>
            حجم کشتار شده:
            {selectedPoultryInfo?.killedQuantity?.toLocaleString()} قطعه
          </Typography>
          <Typography>
            نژاد: {selectedPoultryInfo?.chickenBreed?.toLocaleString()}
          </Typography>

          <Typography>
            تلفات: {selectedPoultryInfo?.totalLosses?.toLocaleString("fa-IR")}
            قطعه
          </Typography>
        </Paper>
      )}

      <TextField
        label="تعداد (قطعه)"
        name="quantity"
        value={formik.values.quantity}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={formik.touched.quantity && Boolean(formik.errors.quantity)}
        helperText={formik.touched.quantity && formik.errors.quantity}
        fullWidth
      />

      <TextField
        label="دلیل افزایش حجم"
        name="message"
        multiline
        rows={3}
        value={formik.values.message}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={formik.touched.message && Boolean(formik.errors.message)}
        helperText={formik.touched.message && formik.errors.message}
        fullWidth
      />

      <Button
        variant="contained"
        fullWidth
        disabled={
          !(
            formik.isValid &&
            formik.values.poultry &&
            formik.values.hatching_key &&
            formik.values.quantity &&
            formik.values.message
          )
        }
        onClick={() => {
          const payload = {
            hatching_key: formik.values.hatching_key,
            quantity: parseInt(formik.values.quantity),
            message: formik.values.message,
            registerer_role: getRoleFromUrl(),
          };

          const action = isEdit
            ? cityEditIncreaseHatchingeService({
                ...payload,
                key: item?.key,
              })
            : cityIncreaseHatchingeService(payload);

          dispatch(action).then((res) => {
            if (res.payload.error) {
              openNotif({
                msg: "مشکلی پیش آمده است!",
                severity: "error",
                vertical: "top",
                horizontal: "center",
              });
            } else {
              openNotif({
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
                vertical: "top",
                horizontal: "center",
              });
              updateTable();
              dispatch(DRAWER({ right: false, bottom: false, content: null }));
            }
          });
        }}
      >
        {isEdit ? "ویرایش" : "ثبت"}
      </Button>
    </Stack>
  );
};
