import { useContext, useEffect, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  Box,
  TextField,
  Typography,
  Button,
  Tooltip,
  FormControlLabel,
  Checkbox,
} from "@mui/material";
import moment from "moment";
import { SPACING } from "../../../../data/spacing";
import { DatePicker } from "@mui/x-date-pickers";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useDispatch, useSelector } from "react-redux";
import { format } from "date-fns-jalali";
// import EditIcon from "@mui/icons-material/Edit";
import axios from "axios";
import { formatTime } from "../../../../utils/formatTime";
import ShowImage from "../../../../components/show-image/ShowImage";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { VetFarmOperationOptions } from "../../../vet-farm/components/vet-farm-operations-options/VetFarmOperationOptions";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { VetFarmEditTrafficCode } from "../../../vet-farm/components/vet-farm-edit-traffic-code/VetFarmEditTrafficCode";
import { vetFarmGetFinishedBarsOverview } from "../../../vet-farm/services/vet-farm-get-bars-overview";
import { Grid } from "../../../../components/grid/Grid";

export const SlaughterManageBars = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [hasDocumentState, setHasDocumentState] = useState(false);
  const handleChangeDocumentState = () => {
    setHasDocumentState(!hasDocumentState);
  };

  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 userKey = useSelector((state) => state.userSlice.userProfile.key);

  const dispatch = useDispatch();

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

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `kill_house_assignment_information/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${
        page ? page : 1
      }&page_size=${perPage}&without_bar_document=${hasDocumentState}`
    );

    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);
  };

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

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

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

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

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

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

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

  useEffect(() => {
    dispatch(
      vetFarmGetFinishedBarsOverview({
        selectedDate1,
        selectedDate2,
        textValue,
        hasDocumentState,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  }, [selectedDate1, selectedDate2, hasDocumentState]);

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

  const getItemState = (item) => {
    let state = "";
    if (item?.wareHouseConfirmation) {
      state = "ورود به انبار";
    } else if (item?.assignmentStateArchive !== "pending") {
      state = "ثبت اطلاعات بار";
    } else {
      if (item.trash === true) {
        state = "حذف شده";
      } else if (item.vetState === "accepted") {
        state = "تایید تخلیه";
      } else if (item.vetState === "pending") {
        state = "در انتظار تخلیه";
      }
    }

    return state;
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        <VetFarmOperationOptions
          key={i}
          item={item}
          updateTable={fetchApiData}
          isComplete
        />,
        <Typography
          key={i}
          style={{ fontSize: "13px", color: item?.trash ? "red" : "black" }}
        >
          {getItemState(item)}
        </Typography>,
        <Typography
          key={i}
          style={{ fontSize: "13px", color: item?.trash ? "red" : "black" }}
        >
          {item.barCode}
        </Typography>,
        formatTime(item.createDate),
        item?.poultryRequest?.freezing
          ? "انجماد"
          : item?.poultryRequest?.export
          ? "صادرات"
          : "عادی",
        <Typography
          key={i}
          variant="body2"
          color={item?.barDocumentStatus?.isError ? "error" : "primary"}
        >
          {item?.barDocumentStatus?.title
            ? item?.barDocumentStatus?.title
            : "-"}
        </Typography>,
        <ShowImage key={i} src={item?.assignmentInfo?.imageWithBar} />,
        item.acceptedRealQuantity?.toLocaleString(),
        item?.acceptedRealWeight?.toLocaleString(),
        item?.weightInfo?.finalIndexWeight?.toLocaleString(),
        `${item.killhouseUser?.name} (${item.killhouseUser?.killHouseOperator?.user?.mobile})`,
        item?.killer
          ? `${item?.killer?.name} (${item?.killer?.killHouseOperator?.user?.mobile})`
          : "-",
        `${item.poultryRequest?.poultry?.user?.fullname} (${item.poultryRequest.poultry?.user?.mobile})`,
        `${item.poultryRequest?.poultry?.unitName}`,
        item?.poultryRequest?.age,
        item.quantity?.toLocaleString(),
        item?.weightInfo?.weight?.toLocaleString(),
        <Grid key={i}>
          <VetFarmEditTrafficCode
            updateTable={fetchApiData}
            killHouseRequestKey={item.key}
            trafficCode={item?.trafficCode}
            isEditable={
              item?.killer?.key &&
              (getRoleFromUrl() === "KillHouse" ||
                getRoleFromUrl() === "AdminX" ||
                getRoleFromUrl() === "VetFarm" ||
                getRoleFromUrl() === "ProvinceOperator" ||
                getRoleFromUrl() === "KillHouseVet" ||
                getRoleFromUrl() === "SuperAdmin" ||
                getRoleFromUrl() === "Supporter")
            }
          />
        </Grid>,
        item?.amount?.toLocaleString() + " ﷼",
        item?.clearanceCode ? item?.clearanceCode : "-",
        item?.quarantineQuantity
          ? item?.quarantineQuantity
          : item?.quarantineCodeState
          ? item?.quarantineCodeState === "contradiction"
            ? "مغایرت کد رهگیری"
            : item?.quarantineCodeState === "noclearance"
            ? "فاقد کد رهگیری"
            : item?.quarantineCodeState === "merge"
            ? "ادغام"
            : "عدم تایید راهداری"
          : "-",
        // item?.realAddCar?.driver
        //   ? `${item?.realAddCar?.driver?.typeCar} (${
        //       item?.realAddCar?.driver?.pelak
        //         ? item?.realAddCar?.driver?.pelak
        //         : "نامشخص"
        //     }) - راننده: ${item?.realAddCar?.driver?.driverName}`
        //   : "-",

        `${item.addCar.driver.typeCar} ${item.addCar.driver.pelak}`,
        `${item.addCar.driver.driverName} (${item.addCar.driver.driverMobile})`,
        item.poultryRequest.chickenBreed,
        item?.weightInfo?.indexWeight?.toLocaleString(),
        item?.poultryRequest?.amount?.toLocaleString() + " ﷼",
        item?.weightInfo?.killHousePrice?.toLocaleString() + " ﷼",
        item?.vetFarm?.vet?.user?.fullname
          ? item?.vetFarm?.vet?.user?.fullname +
            `(${item?.vetFarm?.vet?.user?.mobile})`
          : "فاقد دامپزشک",
        `${item.killPlace}`,
        item.poultryRequest.poultry.address.city.name,
        item?.poultryRequest.sendDate
          ? format(new Date(item?.poultryRequest.sendDate), "yyyy/MM/dd")
          : "-",
        item?.poultryRequest.orderCode,
        item?.wareHouseAcceptedRealQuantity?.toLocaleString(),
        item?.wareHouseAcceptedRealWeight?.toLocaleString(),
        item?.weightLoss?.toLocaleString(),
      ];
    });

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

  return (
    <Box width="100%" mt={2}>
      <Grid
        display="flex"
        alignItems="center"
        justifyContent={"center"}
        direction="row"
        gap={SPACING.SMALL}
      >
        <Grid container justifyContent="center" gap={SPACING.SMALL} xs={12}>
          <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>
            {!!data?.length && (
              <Grid>
                <Tooltip title="خروجی اکسل">
                  <a
                    href={`${
                      axios.defaults.baseURL
                    }bar_excel/?start=${selectedDate1}&end=${selectedDate2}&state=completed&role=${getRoleFromUrl()}&key=${userKey}&search=filter&value=${textValue}`}
                    rel="noreferrer"
                  >
                    <Button color="success">
                      <RiFileExcel2Fill size={32} />
                    </Button>
                  </a>
                </Tooltip>
              </Grid>
            )}
            {(getRoleFromUrl() === "SuperAdmin" ||
              getRoleFromUrl() === "Supporter" ||
              getRoleFromUrl() === "AdminX") && (
              <FormControlLabel
                control={
                  <Checkbox
                    checked={hasDocumentState}
                    onChange={handleChangeDocumentState}
                    name="item4"
                  />
                }
                label="بدون وضعیت سند"
              />
            )}
          </Grid>
          <Grid container mt={2} mb={4} isDashboard>
            <ResponsiveTable
              title={"خلاصه اطلاعات"}
              noPagination
              isDashboard
              columns={[
                "تعداد بارها",
                "حجم بارها",
                "وزن بارها",
                "میانگین وزن",
                "کمترین سن ",
                "بیشترین سن ",
                "میانگین سنی",
                "بارهای دارای کد قرنطینه",
                "حجم بارهای دارای کد قرنطینه",
                "بارهای احراز شده از قرنطینه",
                "حجم بارهای احراز شده از قرنطینه",
                "بارهای فاقد کد قرنطینه",
                "حجم بارهای فاقد کد قرنطینه",
                "بارهایی که در قرنطینه و رصدیار اختلاف دارند",
                "بارهای تکمیل شده کشتارگاه",
                "حجم نهایی در کشتارگاه	",
                "وزن نهایی در کشتارگاه",
                "تعداد بار ورودی به انبار",
                "حجم لاشه های انبار",
                "وزن لاشه های انبار",
                "درصد افت بار انبار",
              ]}
              data={[
                [
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.lenKillRequest?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {dashboardData?.killRequestQuantity?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.killRequestWeight?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {dashboardData?.avgWeight}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.minAge}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {dashboardData?.maxAge}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.avgAge}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {dashboardData?.lenKillRequestHasCode?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.quantityOfKillRequestHasCode?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {dashboardData?.lenKillRequestHasQuarantine?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.quantityOfKillRequestHasQuarantine?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {dashboardData?.lenKillRequestHasNotCode?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.quantityOfKillRequestHasNotCode?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {dashboardData?.differenceBar?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.lenCompleteWithKillHouse?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {dashboardData?.quantityFinalKillHouse?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.weightFinalKillHouse?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {dashboardData?.wareHouseBars?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.wareHouseBarsQuantity?.toLocaleString()}
                  </Typography>,
                  <Typography variant="caption" key={"1"}>
                    {dashboardData?.wareHouseBarsWeight?.toLocaleString()}
                  </Typography>,
                  <Typography
                    variant="caption"
                    key={"1"}
                    style={{ color: "blue" }}
                  >
                    {dashboardData?.wareHouseBarsWeightLose
                      ?.toFixed(2)
                      ?.toLocaleString()}
                  </Typography>,
                ],
              ]}
            />
          </Grid>
          <ResponsiveTable
            data={tableData}
            columns={[
              "ردیف",
              "عملیات",
              "وضعیت",
              "کدبار",
              "تاریخ ثبت خودرو",
              "نوع کشتار",
              "وضعیت سند",
              "سند (بارنامه)",
              "تعداد نهایی",
              "وزن نهایی بار (کیلوگرم)",
              "میانگین وزن نهایی (کیلوگرم)",
              "خریدار",
              "کشتارکن اختصاصی",
              "مشخصات مرغدار",
              "نام فارم",
              "سن مرغ",
              "تعداد اولیه",
              "وزن اولیه بار (کیلوگرم)",
              "کد بهداشتی حمل و نقل",
              "قیمت مرغ زنده‌ی بار",
              "کدرهگیری سامانه قرنطینه",
              "تعداد در قرنطینه",
              // "ماشین واقعی حمل",
              "ماشین",
              "راننده",
              "نژاد",
              "میانگین وزن اولیه (کیلوگرم)",
              "قیمت مرغدار",
              "قیمت کشتارگاه",
              "دامپزشک فارم",
              "محل کشتار",
              "شهر",
              "تاریخ کشتار",
              "کدسفارش کشتار",
              "حجم لاشه",
              "وزن لاشه",
              "درصد افت",
            ]}
            handlePageChange={handlePageChange}
            totalRows={totalRows}
            page={page}
            perPage={perPage}
            handlePerRowsChange={handlePerRowsChange}
            title="بارهای تکمیل شده"
          />
        </Grid>
      </Grid>
    </Box>
  );
};
