import { useContext, useEffect, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { slaughterGetPermissionToVetService } from "../../services/slaughter-get-premisson-to-vet";
import { Box, Switch, TextField, Typography, Button } from "@mui/material";
import moment from "moment";
import { slaughterPermissionToVetService } from "../../services/slaughter-premisson-to-vet";
import { SPACING } from "../../../../data/spacing";
import { DatePicker } from "@mui/x-date-pickers";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useDispatch } from "react-redux";
import { format } from "date-fns-jalali";
import axios from "axios";
import { VetFarmEditTrafficCode } from "../../../vet-farm/components/vet-farm-edit-traffic-code/VetFarmEditTrafficCode";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { slaughterEnterLoadInformationGetDashboard } from "../../services/slaughter-enter-load-information-get-dashboard";
import { Grid } from "../../../../components/grid/Grid";
import { RiSearchLine } from "react-icons/ri";
import { SlaughterEnterInformationOperation } from "../slaughter-enter-information-operation/SlaughterEnterInformationOperation";

export const EnterLoadInformation = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [checked, setChecked] = useState(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 dispatch = useDispatch();

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  useEffect(() => {
    if (getRoleFromUrl() === "KillHouse") {
      dispatch(slaughterGetPermissionToVetService()).then((r) => {
        if (r.payload.data?.length) {
          setChecked(r.payload.data[0]?.allow);
        } else {
          setChecked(false);
        }
      });
    }
  }, []);

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `kill_house_request_complete_information/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

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

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

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

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

  const updateTable = () => {
    fetchDashboardData();
    fetchApiData(1);
  };
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const handleDateChange1 = (date) => {
    setSelectedDate1(date);
  };

  const handleDateChange2 = (date) => {
    setSelectedDate2(date);
  };

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

  useEffect(() => {
    fetchApiData(1);
    fetchDashboardData();
  }, [selectedDate1, selectedDate2, perPage]);

  const handleChange = () => {
    dispatch(
      slaughterPermissionToVetService({
        allow: !checked,
      })
    );
    setChecked(!checked);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        <SlaughterEnterInformationOperation
          key={i}
          item={item}
          updateTable={updateTable}
        />,
        <Typography
          key={i}
          style={{ fontSize: "13px", color: item?.trash ? "red" : "black" }}
        >
          {item.barCode}
        </Typography>,
        <VetFarmEditTrafficCode
          key={i}
          updateTable={fetchApiData}
          killHouseRequestKey={item.key}
          trafficCode={item?.trafficCode}
          isEditable={
            getRoleFromUrl() === "ProvinceOperator" ||
            getRoleFromUrl() === "SuperAdmin" ||
            getRoleFromUrl() === "VetSupervisor" ||
            (item.trash !== true &&
              item.assignmentStateArchive === "pending" &&
              !item?.clearanceCode &&
              (getRoleFromUrl() === "VetFarm" ||
                getRoleFromUrl() === "CityVet"))
          }
        />,
        item?.poultryRequest.sendDate
          ? format(new Date(item?.poultryRequest.sendDate), "yyyy/MM/dd")
          : "-",
        `${item.killhouseUser?.name} (${item.killhouseUser?.killHouseOperator?.user?.mobile})`,
        item?.killer
          ? `${item?.killer?.name} (${item?.killer?.killHouseOperator?.user?.mobile})`
          : "-",
        `${item.poultryRequest?.poultry?.unitName} (${item.poultryRequest.poultry?.user?.mobile})`,
        item?.poultryRequest?.age,
        item.quantity?.toLocaleString(),
        item?.weightInfo?.weight?.toLocaleString(),
        `${item.addCar.driver.typeCar} ${item.addCar.driver.pelak}`,
        `${item.addCar.driver.driverName} (${item.addCar.driver.driverMobile})`,
        item?.poultryRequest?.amount?.toLocaleString() + " ﷼",
        item?.weightInfo?.killHousePrice?.toLocaleString() + " ﷼",
        item.vetAcceptedRealQuantity?.toLocaleString(),
        item.vetAcceptedRealWeight?.toLocaleString(),
        item?.poultryRequest.orderCode,
        item?.barDocumentStatus?.title ? item?.barDocumentStatus?.title : "-",
        item?.finalBarState,
        item?.poultryRequest?.freezing ? "انجماد" : "عادی",
      ];
    });

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

  const [dashboardData, setDashboardData] = useState([]);

  const fetchDashboardData = () => {
    dispatch(
      slaughterEnterLoadInformationGetDashboard({
        selectedDate1,
        selectedDate2,
        text: textValue,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  return (
    <Box width="100%">
      {getRoleFromUrl() === "KillHouse" && (
        <Grid container alignItems="end" justifyContent={"center"}>
          <Grid container alignItems="center" xs={12} justifyContent={"end"}>
            <Grid>
              <Typography color="gray">
                دسترسی دامپزشک برای وارد کردن اطلاعات بار
              </Typography>
            </Grid>
            <Grid>
              <Switch
                checked={checked}
                onChange={handleChange}
                name="switch-state"
                inputProps={{ "aria-label": "switch with state" }}
              />
            </Grid>
          </Grid>
        </Grid>
      )}
      <Grid container alignItems="center" gap={SPACING.SMALL} xs={12}>
        <Grid style={{ width: "150px" }}>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => <TextField {...params} />}
            value={selectedDate1}
            onChange={(e) => {
              handleDateChange1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid style={{ width: "150px" }}>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => <TextField {...params} />}
            value={selectedDate2}
            onChange={(e) => {
              handleDateChange2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <form onSubmit={handleSubmit}>
          <TextField
            autoComplete="off"
            size="small"
            label="جستجو"
            variant="outlined"
            style={{ width: 250 }}
            onChange={handleTextChange}
          />
          <Button
            // disabled={!textValue}
            type="submit"
            onClick={handleSubmit}
            endIcon={<RiSearchLine />}
          >
            جستجو
          </Button>
        </form>
      </Grid>

      <Grid
        container
        justifyContent="center"
        gap={SPACING.SMALL}
        xs={12}
        mt={2}
      >
        <Grid container mt={2} mb={4} isDashboard>
          <ResponsiveTable
            noPagination
            columns={[
              "تعداد بار",
              "مجموع تعداد اولیه",
              "مجموع وزن اولیه (کیلوگرم)",
              "مجموع تعداد تحویلی دامپزشک",
              "مجموع وزن تحویلی دامپزشک (کیلوگرم)",
            ]}
            data={[
              [
                dashboardData?.lenKillHouseRequest?.toLocaleString(),
                dashboardData?.firstQuantity?.toLocaleString(),
                dashboardData?.firstWeight?.toLocaleString(),
                dashboardData?.vetAcceptedRealQuantity?.toLocaleString(),
                dashboardData?.vetAcceptedRealWeight?.toLocaleString(),
              ],
            ]}
            title={"خلاصه اطلاعات"}
            isDashboard
          />
        </Grid>

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