import React, { useEffect, useState, useCallback } from "react";
import {
  Button,
  Checkbox,
  FormControl,
  FormControlLabel,
  InputLabel,
  IconButton,
  MenuItem,
  Select,
  TextField,
  Tooltip,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import { SlaughterSubmitRealInventory } from "../slaughter-submit-real-inventory/SlaughterSubmitRealInventory";
import SettingsIcon from "@mui/icons-material/Settings";
import { formatJustDate } from "../../../../utils/formatTime";
import { RiSearchLine } from "react-icons/ri";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterInventoryInProvinceBars = ({ type }) => {
  const [selectedDate1, setSelectedDate1] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [selectedDate2, setSelectedDate2] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );
  const dispatch = useDispatch();

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const [withDate, setWithDate] = useState(type === "entered" ? true : false);
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);
  const [quota, setQuota] = useState("all");

  const fetchApiData = useCallback(
    async (page) => {
      dispatch(LOADING_START());
      const response = await axios.get(
        `bars_for_kill_house/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${
          withDate
            ? `&date1=${selectedDate1}${
                checkPathStartsWith("slaughter")
                  ? `&role_key=${selectedSubUser?.key}`
                  : ""
              }&date2=${selectedDate2}`
            : ``
        }&page=${page}&page_size=${perPage}&type=${type}&quota=${quota}`
      );
      dispatch(LOADING_END());
      setData(response.data.results);
      setTotalRows(response.data.count);
    },
    [
      textValue,
      withDate,
      selectedDate1,
      selectedDate2,
      perPage,
      type,
      quota,
      dispatch,
      setData,
      selectedSubUser?.key,
      setTotalRows,
    ]
  );

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.barCode,
        formatJustDate(item?.poultryRequest?.date),
        `${item?.poultryRequest?.poultryName} (${item?.poultryRequest?.poultryMobile}) - ${item?.poultryRequest?.poultryUserName}`,
        item?.poultryRequest?.poultryCity,
        `${item?.killhouseUser?.killer ? "کشتارکن" : "کشتارگاه"} ${
          item?.killhouseUser?.name
        } (${item?.killhouseUser?.killHouseOperator?.user?.mobile})`,
        item?.poultryRequest?.poultryReqOrderCode,
        item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی",
        item?.killer
          ? `${item?.killer?.name} (${item?.killer?.killHouseOperator?.user?.mobile})`
          : "-",
        item?.poultryRequest?.freeSaleInProvince ? "آزاد" : "دولتی",
        item?.poultryRequest?.chickenBreed,
        `${item?.addCar?.driver?.driverName}/${item?.addCar?.driver?.typeCar}`,
        item?.addCar?.driver?.healthCode
          ? item?.addCar?.driver?.healthCode
          : "-",
        item?.clearanceCode ? item?.clearanceCode : "-",
        item?.acceptedRealQuantity?.toLocaleString(),
        item?.acceptedRealWeight?.toLocaleString(),
        item?.weightInfo?.state,
        item?.wareHouseAcceptedRealQuantity.toLocaleString(),
        item?.wareHouseAcceptedRealWeight.toLocaleString(),
        item?.weightInfo?.weightLoss
          ? item?.weightInfo?.weightLoss?.toFixed(2) + "%"
          : 0 + "%",
        item?.weightInfo?.inputLoss
          ? item?.weightInfo?.inputLoss?.toFixed(2) + "%"
          : 0 + "%",
        item?.dateOfWareHouse ? formatJustDate(item?.dateOfWareHouse) : "-",
        <Tooltip title="ورود بار به انبار" key={i}>
          <IconButton
            size={"small"}
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ثبت موجودی واقعی",
                  content: (
                    <SlaughterSubmitRealInventory
                      updateTable={updateTable}
                      item={item}
                    />
                  ),
                })
              );
            }}
          >
            <SettingsIcon fontSize="small" />
          </IconButton>
        </Tooltip>,
      ];
    });

    setTableData(d);
  }, [data]);

  useEffect(() => {
    fetchApiData(1);
  }, [fetchApiData]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `bars_for_kill_house/?role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&search=filter&value=${textValue}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }&page=${1}&page_size=${perPage}&type=${type}&quota=${quota}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Grid
          container
          style={{
            borderStyle: "solid",
            borderWidth: "1px",
            padding: "10px",
            borderRadius: "15px",
            borderColor: "gray",
            justifyContent: "left",
          }}
        >
          {type === "notentered" && (
            <Grid>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={withDate}
                    onChange={() => setWithDate(!withDate)}
                    color="primary"
                  />
                }
              />
            </Grid>
          )}

          <Grid>
            <DatePicker
              disabled={!withDate}
              label="از تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  style={{ width: "160px" }}
                  {...params}
                />
              )}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              disabled={!withDate}
              label="تا تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  style={{ width: "160px" }}
                  {...params}
                />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        </Grid>
        <Grid>
          <FormControl size="small" style={{ minWidth: 150 }}>
            <InputLabel>نوع فروش</InputLabel>
            <Select
              value={quota}
              onChange={(e) => setQuota(e.target.value)}
              label="نوع فروش"
            >
              <MenuItem value="all">همه</MenuItem>
              <MenuItem value="governmental">دولتی</MenuItem>
              <MenuItem value="free">آزاد</MenuItem>
            </Select>
          </FormControl>
        </Grid>
        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "کدبار",
          "تاریخ کشتار",
          "مرغدار",
          "شهر مرغدار",
          "خریدار",
          "کدسفارش",
          "کشتار",
          "کشتارکن",
          "فروش",
          "نژاد",
          "راننده/نوع خودرو",
          "کدبهداشتی حمل و نقل",
          "کدرهگیری سامانه قرنطینه",
          "حجم بار (قطعه)",
          "وزن بار (کیلوگرم)",
          "وضعیت",
          "حجم لاشه",
          "وزن لاشه",
          "درصد افت در لحظه",
          "درصد افت ورود به انبار",
          "تاریخ ورود به انبار",
          "عملیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={
          type === "entered"
            ? "وارد شده به انبار (کشتار داخل استان)"
            : "در انتظار ورود به انبار (کشتار داخل استان)"
        }
      />
    </Grid>
  );
};
