import { Grid, IconButton, TextField, Tooltip } from "@mui/material";
import { SPACING } from "../../../../data/spacing";
import { useFormik } from "formik";
import moment from "moment";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch, useSelector } from "react-redux";
import { slaughterGetActiveRequests } from "../../services/slaughter-get-active-requests";
import { useContext, useEffect, useState } from "react";
import EditIcon from "@mui/icons-material/Edit";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { slaughterGetAllocatedCarsService } from "../../services/slaughter-get-allocated-cars";
import { AppContext } from "../../../../contexts/AppContext";
import { format } from "date-fns-jalali";
import { DatePicker } from "@mui/x-date-pickers";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
import { useReactToPrint } from "react-to-print";
import { useRef } from "react";
import SlaughterSendKillerInvoice from "../slaughter-send-killer-invoice/SlaughterSendKillerInvoice";
import { useSystemName } from "../../../../utils/getSystemName";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { provincePolicyGetSLaughterSubmitBuyingPriceStatus } from "../../../province/services/province-policy-get-slaughter-buying-price-status";
import { SlaughterSubmitChickenPrice } from "../slaughter-submit-chicken-price/SlaughterSubmitChickenPrice";
import { SlaughterAllocatedCarToRequestOperation } from "../slaughter-allocate-car-to-request-operation/SlaughterAllocatedCarToRequestOperation";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterAllocateCarToRequests = () => {
  const componentRef = useRef();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [data, setData] = useState();
  const [dataTable, setDataTable] = useState([]);
  const [allocatedDataTable, setAllocatedDataTable] = useState([]);
  const { slaughterActiveRequests, slaughterGetAllocatedCars } = useSelector(
    (state) => state.slaughterSlice
  );

  const systemName = useSystemName();
  const dispatch = useDispatch();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  const [submitStatus, SetSubmitStatus] = useState();

  const fetchData = () => {
    dispatch(
      slaughterGetActiveRequests({
        isCar: true,
        selectedDate1,
        selectedDate2,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
    dispatch(
      slaughterGetAllocatedCarsService({
        selectedDate1,
        selectedDate2,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
    dispatch(
      provincePolicyGetSLaughterSubmitBuyingPriceStatus({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      SetSubmitStatus(r.payload.data.allow);
    });
  };

  useEffect(() => {
    fetchData();
  }, [selectedDate1, selectedDate2, selectedSubUser?.key]);

  const printPDF = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: "حواله خرید",
  });
  const updateTable = () => {
    fetchData();
  };

  const setPdfOptions = (item) => {
    setData(item);
  };

  useEffect(() => {
    const d = slaughterActiveRequests?.map((item, i) => {
      return [
        i + 1,
        item.orderCode,
        item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی",
        item?.freeSaleInProvince ? "آزاد" : "دولتی",
        item?.directBuying ? "خرید مستقیم" : "اتحادیه",
        format(new Date(item?.sendDate), "yyyy/MM/dd"),
        `${item.poultryName} (${item.poultryMobile})`,
        `${item.killHouseName} (${item.killHouseMobile})`,
        `${item.province}/${item.city}`,
        item.age,
        item.indexWeight,
        item?.totalWeight.toLocaleString(),
        item.mainQuantity.toLocaleString() + " قطعه",
        item.amount.toLocaleString() + " ﷼",
        item.allocatedQuantity.toLocaleString() + " قطعه",
        item.remainQuantity.toLocaleString() + " قطعه",
        item?.killHousePrice > 0 ? (
          <Grid container alignItems="center" gap={1} key={i}>
            {item?.killHousePrice?.toLocaleString() + " ریال"}
            {formatJustDate(item?.sendDate) === formatJustDate(new Date()) ? (
              <IconButton
                size="small"
                color="primary"
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "ویرایش قیمت مرغ زنده",
                      content: (
                        <SlaughterSubmitChickenPrice
                          item={item}
                          fetchData={fetchData}
                        />
                      ),
                    })
                  );
                }}
              >
                <EditIcon fontSize="small" />
              </IconButton>
            ) : null}
          </Grid>
        ) : (
          <span key={i}>0</span>
        ),

        <SlaughterAllocatedCarToRequestOperation
          key={i}
          updateTable={updateTable}
          item={item}
          submitStatus={submitStatus}
        />,
        // <IconButton
        //   key={i}
        //   aria-label="delete"
        //   color="primary"
        //   onClick={() => navigate(ROUTE_SLAUGHTER_FILE + item.poultryReqId)}
        // >
        //   <PlagiarismIcon />
        // </IconButton>,
      ];
    });

    setDataTable(d);
  }, [slaughterActiveRequests, submitStatus]);

  useEffect(() => {
    const d = slaughterGetAllocatedCars
      ?.filter((item) => item.vetState === "pending")
      .map((item, i) => {
        return [
          i + 1,
          item?.orderCode,
          item?.barcod,
          item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی",
          item?.freeSaleInProvince ? "آزاد" : "دولتی",
          formatJustDate(item?.sendDate),
          formatTime(item?.killHouseCreateDate),
          `${item?.poultryName} (${item.poultryMobile})`,
          `${item?.killHouseName} (${item.killHouseMobile})`,
          item?.killer
            ? `${item?.killer?.killerName} (${item?.killer?.killerMobile})`
            : "-",
          item?.driverName,
          item?.typeCar,
          item?.pelak,
          // item?.realCar
          //   ? `${item?.realCar?.realTypeCar} (${
          //       item?.realCar?.realPelak ? item?.realCar?.realPelak : "نامشخص"
          //     }) - راننده: ${item?.realCar?.realDriverName}`
          //   : "-",
          item?.acceptedRealQuantity.toLocaleString() + " قطعه",
          item?.acceptedRealWeight.toLocaleString(),
          item?.amount?.toLocaleString() + " ﷼",
          item?.trafficCode,
          item?.barAmount?.toLocaleString() + " ﷼",
          <Grid key={i} container gap={1}>
            <SlaughterAllocatedCarToRequestOperation
              key={i}
              item={item}
              updateTable={updateTable}
              isAllocatedCar={true}
              selectedDate1={selectedDate1}
              selectedDate2={selectedDate2}
            />

            {systemName === "استان اردبیل" ? (
              <Tooltip title="خروجی PDF">
                <IconButton
                  onClick={() => {
                    printPDF();
                    setPdfOptions(item);
                  }}
                  size={"large"}
                  aria-label="pdf"
                  color="success"
                >
                  <PictureAsPdfIcon />
                </IconButton>
              </Tooltip>
            ) : null}
          </Grid>,
        ];
      });

    setAllocatedDataTable(d);
  }, [slaughterGetAllocatedCars]);

  const [tableDataCol] = useState([
    "ردیف",
    "کد سفارش",
    "کشتار",
    "فروش",
    "درخواست",
    "تاریخ کشتار",
    "مرغدار",
    "خریدار",
    "استان/شهر",
    "سن",
    "میانگین وزن",
    "وزن کل (کیلوگرم)",
    "تعداد",
    "قیمت مرغدار",
    "تخصیص به خودرو",
    "مانده قابل تخصیص",
    "قیمت کشتارگاه",
    "عملیات",
  ]);

  const formik = useFormik({
    initialValues: {
      capacity: "",
      recieveTime: "",
      recieveDate: moment(Date()).format("YYYY-MM-DD hh:mm:ss"),
    },
    validationSchema: Yup.object({
      capacity: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      recieveTime: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
    }),
  });

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

  return (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={SPACING.SMALL}
      mt={SPACING.MEDIUM}
    >
      {data && (
        <div style={{ visibility: "hidden", position: "absolute" }}>
          <SlaughterSendKillerInvoice
            ref={componentRef}
            date={selectedDate1}
            amount={data?.quantity}
            breeder={data?.poultryName}
            buyer={data?.killHouseName}
          />
        </div>
      )}

      <Grid container alignItems="center" gap={SPACING.SMALL}>
        <Grid>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
      </Grid>
      <ResponsiveTable
        paginated
        title="در انتظار تخصیص خودرو"
        columns={tableDataCol}
        data={dataTable}
      />
      <ResponsiveTable
        title="خودروهای تخصیص داده شده"
        paginated
        columns={[
          "ردیف",
          "کد سفارش",
          "کد بار",
          "کشتار",
          "فروش",
          "تاریخ کشتار",
          "تاریخ ثبت خودرو",
          "مرغدار",
          "خریدار",
          "کشتارکن اختصاصی",
          "راننده",
          "ماشین",
          "پلاک",
          "تعداد",
          "وزن (کیلوگرم)",
          "قیمت مرغ زنده",
          "کد حمل و نقل",
          "قیمت مرغ زنده‌ی بار",
          "عملیات",
        ]}
        data={allocatedDataTable}
      />
    </Grid>
  );
};
