import {
  Button,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import axios from "axios";
import { useContext, useEffect, useState } from "react";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { formatTime, formatJustDate } from "../../../../utils/formatTime";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { CityManageHatchingsOperations } from "../city-manage-hatchings-operations/CityManageHatchingsOperations";
import { useDispatch, useSelector } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { cityGetHatchingInfoFull } from "../../services/city-get-hatching-info-full";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  // DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import ShowImage from "../../../../components/show-image/ShowImage";
import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye";
import {
  ROUTE_ADMINXـHATCHINGS,
  ROUTE_CITY_JIHADـHATCHINGS,
  ROUTE_CITY_POULTRYـHATCHINGS,
  ROUTE_PROVINCE_SUPERVISORـHATCHINGS,
  ROUTE_PROVINCEـHATCHINGS,
  ROUTE_SUPER_ADMINـHATCHINGS,
  ROUTE_SUPPORTERـHATCHINGS,
} from "../../../../routes/routes";
import { useNavigate } from "react-router-dom";

// import { CityHatchingShowTableDetail } from "../city-hatching-show-table-detail/CityHatchingShowTableDetail";

export const CityHatchings = ({ readOnly }) => {
  const dispatch = useDispatch();

  const isReadOnly = readOnly || false;
  const [selectedAge1, setSelectedAge1] = useState(0);
  const [selectedAge2, setSelectedAge2] = useState(0);
  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 navigate = useNavigate();

  const [openNotif] = useContext(AppContext);

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

  const hatchingAdded = useSelector((state) => state.citySlice.hatchingAdded);

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

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `poultry_hatching?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&age1=${
        selectedAge1 ? selectedAge1 : 0
      }&age2=${
        selectedAge2 ? selectedAge2 : 0
      }&search=filter&value=${textValue}`
    );
    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);
  }, [dispatch, perPage]);

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

  // const killedNumber = (item) => {
  //   let killedNumber = "";
  //   killedNumber = item.quantity - item.losses - item.leftOver;
  //   return killedNumber;
  // };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        <CityManageHatchingsOperations
          selectedAge1={null}
          selectedAge2={null}
          updateTable={updateTable}
          item={item}
          key={"4"}
          readOnly={isReadOnly}
        />,
        <Tooltip placement="left" title="جزئیات جوجه ریزی" key={item?.key}>
          <IconButton
            color="primary"
            onClick={() => {
              navigate(
                getRoleFromUrl() === "AdminX"
                  ? `${ROUTE_ADMINXـHATCHINGS}/${item.key}`
                  : getRoleFromUrl() === "Supporter"
                  ? `${ROUTE_SUPPORTERـHATCHINGS}/${item.key}`
                  : getRoleFromUrl() === "SuperAdmin"
                  ? `${ROUTE_SUPER_ADMINـHATCHINGS}/${item.key}`
                  : getRoleFromUrl() === "CityPoultry"
                  ? `${ROUTE_CITY_POULTRYـHATCHINGS}/${item.key}`
                  : getRoleFromUrl() === "ProvinceSupervisor"
                  ? `${ROUTE_PROVINCE_SUPERVISORـHATCHINGS}/${item.key}`
                  : getRoleFromUrl() === "ProvinceOperator"
                  ? `${ROUTE_PROVINCEـHATCHINGS}/${item.key}`
                  : getRoleFromUrl() === "CityJahad"
                  ? `${ROUTE_CITY_JIHADـHATCHINGS}/${item.key}`
                  : ""
              );
            }}
          >
            <RemoveRedEyeIcon />
          </IconButton>
        </Tooltip>,
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        <Tooltip
          disableHoverListener={
            !(item?.killingInfo?.violationMessage && item?.violation)
          }
          key={item?.key}
          title={
            item?.violation
              ? `متن گزارش تخلف: ${item?.killingInfo?.violationMessage}`
              : null
          }
          sx={{
            "&:hover": {
              cursor: item?.violation ? "pointer" : "default",
            },
          }}
          placement="top"
        >
          <Typography
            variant="body2"
            color={item?.violation ? "error" : "primary"}
          >
            {item?.violation ? "پیگیری" : "عادی"}
          </Typography>
        </Tooltip>,
        item?.licenceNumber,
        item?.poultry?.breedingUniqueId,
        item?.CertId,
        // item?.commitmentType === "free" ? "آزاد" : "دولتی",
        item?.poultry?.unitName || "-",
        `${item?.poultry?.userprofile?.fullName ?? "-"} (${
          item?.poultry?.userprofile?.mobile ?? "-"
        }) ${item?.violationReport ? "✉️" : ""}`,
        item?.InteractTypeName ? (
          <Typography
            variant="body2"
            color={item?.hasTenant ? "success.main" : ""}
            fontWeight={item?.hasTenant ? "bold" : "normal"}
          >
            {item?.InteractTypeName}
          </Typography>
        ) : (
          "-"
        ),
        item?.PersonTypeName,
        item?.UnionTypeName,
        `${item?.poultry?.address?.city?.name ?? "-"}/${
          item?.poultry?.cityOperator
            ? item?.poultry?.cityOperator
            : "بدون تعاونی"
        }`,
        item?.vetFarm?.vetFarmMobile
          ? `${item?.vetFarm?.vetFarmFullName} (${item?.vetFarm?.vetFarmMobile})`
          : "-",
        item.hall,
        item.period,
        formatTime(item?.createDate),
        formatTime(item?.date),
        item?.poultry?.killingAveAge?.toLocaleString(),
        item?.predicateDate ? formatJustDate(item?.predicateDate) : "-",
        item.chickenBreed,
        item.age,
        item?.quantity?.toLocaleString(),
        item?.increaseQuantity?.toLocaleString(),
        `${item.losses} (%${((item.losses * 100) / item.quantity).toFixed(0)})`,
        <Tooltip
          key={item?.key}
          placement="top"
          title="جهت مشاهده ثبت کننده تلفات کلیک کنید"
        >
          <Button
            // variant="outlined"
            style={{ color: "rgba(0,0,0,0.87)" }}
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ویرایش تعداد جوجه ریزی",
                  content: (
                    <Grid container xs={12}>
                      {!item?.directLossesInputer &&
                      !item?.directLossesInputer ? (
                        <Typography variant="body1">
                          برای این جوجه ریزی تلفاتی ثبت نشده است.
                        </Typography>
                      ) : (
                        <Grid xs={12}>
                          <Typography variant="body1">
                            ثبت کننده تلفات اتحادیه:{" "}
                            {item?.directLossesInputer
                              ? `${
                                  item?.directLossesInputer
                                } در تاریخ ${formatJustDate(
                                  item?.directLossesDate
                                )}`
                              : " - "}
                          </Typography>
                          <Typography variant="body1">
                            ویرایش کننده تلفات اتحادیه:
                            {item?.directLossesEditor
                              ? `${
                                  item?.directLossesEditor
                                } در تاریخ ${formatJustDate(
                                  item?.directLossesLastEditDate
                                )}`
                              : " - "}
                          </Typography>
                        </Grid>
                      )}
                    </Grid>
                  ),
                })
              );
            }}
          >
            {`${item?.directLosses?.toLocaleString()} (%${(
              (item.directLosses * 100) /
              item.quantity
            ).toFixed(0)})`}
          </Button>
        </Tooltip>,
        `${item?.totalLosses?.toLocaleString()} (%${(
          (item.totalLosses * 100) /
          item.quantity
        ).toFixed(0)})`,
        `${item?.totalCommitmentQuantity?.toLocaleString()}`,
        `${item?.totalFreeCommitmentQuantity?.toLocaleString()}`,
        `${item?.governmentalQuantity?.toLocaleString()}`,
        `${item?.governmentalKilledQuantity?.toLocaleString()}`,
        `${item?.freeQuantity?.toLocaleString()}`,
        `${item?.freeKilledQuantity?.toLocaleString()}`,
        `${item?.outProvinceKilledQuantity?.toLocaleString()}`,
        `${item?.outProvinceKilledWeight?.toLocaleString()}`,
        `${item?.barDifferenceRequestQuantity?.toLocaleString()}`,
        `${item?.barDifferenceRequestWeight?.toLocaleString()}`,
        `${item?.killingInfo?.provinceKillRequests?.toLocaleString()}`,
        `${item?.killingInfo?.provinceKillRequestsQuantity?.toLocaleString()}`,
        `${item?.killingInfo?.provinceKillRequestsWeight?.toLocaleString()}`,
        item?.killedQuantity?.toLocaleString() +
          ` (%${((item?.killedQuantity * 100) / item.quantity).toFixed(0)})`,
        item?.leftOver?.toLocaleString(),
        `%${((item?.leftOver * 100) / item?.quantity).toFixed(0)}`,
        // item?.totalCommitment?.toLocaleString(),

        `%${((item.totalLosses * 100) / item.quantity).toFixed(0)}`,
        `%${((item?.killedQuantity * 100) / item.quantity).toFixed(0)}`,
        `%${((item?.leftOver * 100) / item?.quantity).toFixed(0)}`,
        `%${(
          ((item?.killedQuantity + item?.totalLosses) * 100) /
          item?.quantity
        ).toFixed(0)}`,

        item?.samasatDischargePercentage
          ? `%${item?.samasatDischargePercentage}`
          : "-",
        item?.totalCommitment?.toLocaleString(),
        item?.governmentalKilledQuantity?.toLocaleString(),
        item?.freeKilledQuantity?.toLocaleString(),
        item?.totalAverageKilledWeight?.toLocaleString(),
        item?.totalKilledWeight?.toLocaleString(),
        item?.activeKill?.activeKill ? "دارد" : "ندارد",
        item?.activeKill?.countOfRequest ? item.activeKill.countOfRequest : "-",
        item?.killingInfo?.killHouseRequests?.toLocaleString(),
        item?.killingInfo?.killHouseRequestsFirstQuantity?.toLocaleString(),
        item?.killingInfo?.killHouseRequestsFirstWeight?.toLocaleString(),
        item?.killingInfo?.barCompleteWithKillHouse?.toLocaleString(),
        item?.killingInfo?.acceptedRealWightFinal?.toLocaleString(),
        item?.chainKilledQuantity?.toLocaleString(),
        item?.chainKilledWeight?.toLocaleString(),
        item?.exportKilledQuantity?.toLocaleString(),
        item?.exportKilledWeight?.toLocaleString(),
        item?.killingInfo?.wareHouseBars?.toLocaleString(),
        item?.killingInfo?.wareHouseBarsQuantity?.toLocaleString(),
        item?.killingInfo?.wareHouseBarsWeight?.toLocaleString(),
        item?.killingInfo?.wareHouseBarsWeightLose?.toFixed(2),
        item.lastChange
          ? `${item.lastChange.fullName} (${getFaUserRole(
              item.lastChange.role
            )}) در تاریخ ${formatTime(item.lastChange.date)}`
          : "-",
        item.latestHatchingChange
          ? `${item.latestHatchingChange.fullName} (${getFaUserRole(
              item.latestHatchingChange.role
            )}) در تاریخ ${formatTime(item.latestHatchingChange.date)}`
          : "-",
        item?.violationReport ? (
          <Button
            key={item?.key}
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "گزارش ",
                  content: (
                    <SimpleTable
                      columns={[
                        "ثبت کننده",
                        "تاریخ ثبت",
                        "تخلف",
                        "متن گزارش",
                        "سند",
                      ]}
                      data={[
                        [
                          item?.violationReporter,
                          formatJustDate(item?.violationReportDate),
                          item?.violation ? "دارد" : "ندارد",
                          item?.violationReport,
                          <Grid
                            key={item?.key}
                            container
                            xs={12}
                            justifyContent="center"
                            gap={1}
                          >
                            {item?.violationImage?.map((option) => (
                              <ShowImage key={i} src={option} />
                            ))}
                          </Grid>,
                        ],
                      ]}
                    />
                  ),
                })
              );
            }}
          >
            مشاهده گزارش
          </Button>
        ) : (
          "بدون گزارش"
        ),
      ];
    });

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());
    dispatch(
      cityGetHatchingInfoFull({
        age1: selectedAge1,
        age2: selectedAge2,
        tab: "active",
        textValue: textValue,
      })
    );
    try {
      const response = await axios.get(
        `poultry_hatching/?role=${getRoleFromUrl()}&age1=${
          selectedAge1 ? selectedAge1 : 0
        }&age2=${
          selectedAge2 ? selectedAge2 : 0
        }&search=filter&value=${textValue}&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 handleRemoveFilter = async (event) => {
    event.preventDefault();
    setSelectedAge1(0);
    setSelectedAge2(0);
    dispatch(LOADING_START());
    setTextValue("");
    dispatch(
      cityGetHatchingInfoFull({
        age1: 0,
        age2: 0,
        tab: "active",
        textValue: textValue,
      })
    );
    try {
      const response = await axios.get(
        `poultry_hatching?role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&search=filter&value=${textValue}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      dispatch(LOADING_END());
    }
  };

  const [lastUpdateData, setLastUpdateData] = useState();

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await axios.get(`last_update/?type=poultry_hatching`);
        setLastUpdateData(response.data);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    }

    fetchData();
  }, []);

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      paddingTop={2}
      mb={1}
      xs={12}
      mt={2}
    >
      <form onSubmit={handleSubmit} style={{ flex: 1 }}>
        <Grid container alignItems="center" gap={SPACING.SMALL} xs={12}>
          <Grid sx={{ width: { xs: "72px", sm: "80px" } }}>
            <TextField
              fullWidth
              size="small"
              label="از سن"
              id="outlined-controlled"
              value={selectedAge1}
              onChange={(event) => {
                setSelectedAge1(event.target.value);
              }}
            />
          </Grid>
          <Grid sx={{ width: { xs: "72px", sm: "80px" } }}>
            <TextField
              fullWidth
              size="small"
              label="تا سن"
              id="outlined-controlled"
              value={selectedAge2}
              onChange={(event) => {
                setSelectedAge2(event.target.value);
              }}
            />
          </Grid>
          <TextField
            id="outlined-basic"
            size="small"
            label="جستجو"
            variant="outlined"
            value={textValue}
            sx={{ maxWidth: { xs: "100%", sm: 250 } }}
            onChange={handleTextChange}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                handleSubmit(e);
              }
            }}
          />
          <Button type="submit" endIcon={<RiSearchLine />}>
            جستجو
          </Button>
          <Tooltip title="خروجی اکسل" px={0}>
            <Button
              color="success"
              onClick={() => {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                  severity: "success",
                });
                const link = `${
                  axios.defaults.baseURL
                }0/hatching_excel/?role=${getRoleFromUrl()}&key=${userKey}&age1=${
                  selectedAge1 ? selectedAge1 : 0
                }&age2=${
                  selectedAge2 ? selectedAge2 : 0
                }&search=filter&value=${textValue}`;
                window.location.href = link;
              }}
            >
              <RiFileExcel2Fill size={32} />
            </Button>
          </Tooltip>
        </Grid>
      </form>
      <Button onClick={handleRemoveFilter} color="error">
        حذف فیلتر
      </Button>
    </Grid>
  );
  const { hatchingInfoFull } = useSelector((state) => state.citySlice);

  useEffect(() => {
    dispatch(
      cityGetHatchingInfoFull({
        age1: selectedAge1,
        age2: selectedAge2,
        tab: "active",
        textValue: textValue,
      })
    );
  }, []);

  return (
    <Grid alignItems="center" justifyContent="center" mt={2}>
      <Grid alignItems="center" justifyContent="center" isDashboard xs={12}>
        <ResponsiveTable
          noPagination
          isDashboard
          title={
            lastUpdateData &&
            `آخرین بروزرسانی : ${formatTime(lastUpdateData)} ${"‌ ‌"}`
          }
          columns={[
            "تعداد فارم",
            "تعداد جوجه ریزی",
            "حجم کل جوجه ریزی",
            "حجم باقی مانده در سالن",
            "حجم کشتار شده",
            "وزن کشتار شده",
            "حجم کل تلفات",
            "حجم تلفات اتحادیه",
            "حجم تلفات دامپزشک",
            "مانده سالن ( 20 تا 30 روزه)",
            "مانده سالن ( 30 تا 40 روزه)",
            "مانده سالن ( 40 تا 50 روزه)",
            "مانده سالن ( 50 تا 60 روزه)",
            "بیشتر از 60 روزه",
          ]}
          data={[
            [
              hatchingInfoFull?.poultries?.toLocaleString(),
              hatchingInfoFull?.hatchings?.toLocaleString(),
              hatchingInfoFull?.totalHatchingQuantity?.toLocaleString(),
              hatchingInfoFull?.totalHatchingLeftOverQuantity?.toLocaleString(),
              hatchingInfoFull?.totalHatchingKilledQuantity?.toLocaleString(),
              hatchingInfoFull?.totalHatchingKilledWeight?.toLocaleString(),
              hatchingInfoFull?.totalHatchingAllLosses?.toLocaleString(),
              hatchingInfoFull?.totalHatchingUnionLosses?.toLocaleString(),
              hatchingInfoFull?.totalHatchingVetLosses?.toLocaleString(),
              hatchingInfoFull?.age2030?.toLocaleString(),
              hatchingInfoFull?.age3040?.toLocaleString(),
              hatchingInfoFull?.age4050?.toLocaleString(),
              hatchingInfoFull?.age5060?.toLocaleString(),
              hatchingInfoFull?.ageMoreThan60?.toLocaleString(),
            ],
          ]}
        />
      </Grid>

      {tableTitle}

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