import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  Checkbox,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} 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 ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { CityHatchingsArchiveOperations } from "../city-hatchings-archive-operations/CityHatchingsArchiveOperations";
import { cityGetHatchingInfoFull } from "../../services/city-get-hatching-info-full";
import { AppContext } from "../../../../contexts/AppContext";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import ShowImage from "../../../../components/show-image/ShowImage";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { RiFileExcel2Fill } from "react-icons/ri";
import { RiSearchLine } from "react-icons/ri";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import { useNavigate } from "react-router-dom";
import {
  ROUTE_ADMINXـHATCHINGS,
  ROUTE_CITY_POULTRYـHATCHINGS,
  ROUTE_CITY_VISOR_STATICSـHATCHINGS_DETAILS,
  ROUTE_PROVINCE_SUPERVISORـHATCHINGS,
  ROUTE_PROVINCEـHATCHINGS,
  ROUTE_SUPER_ADMINـHATCHINGS,
  ROUTE_SUPPORTERـHATCHINGS,
} from "../../../../routes/routes";
import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye";

export const CityHatchingsArchive = ({ readOnly }) => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const { hatchingInfoFull } = useSelector((state) => state.citySlice);
  const navigate = useNavigate();
  const dispatch = useDispatch();
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

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

  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 [withDate, setWithDate] = useState(false);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `poultry_hatching/?archive=true&search=filter&value=${textValue}&role=${getRoleFromUrl()}
      &key=${userKey}&page=${page}&page_size=${perPage}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }`
    );

    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 updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        <CityHatchingsArchiveOperations
          key={i}
          item={item}
          updateArchive={updateTable}
          readOnly={readOnly}
        />,
        <Tooltip placement="left" title=" جزئیات" key={i}>
          <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() === "province"
                  ? `${ROUTE_PROVINCEـHATCHINGS}/${item.key}`
                  : getRoleFromUrl() === "CityJahad"
                  ? `${ROUTE_CITY_VISOR_STATICSـHATCHINGS_DETAILS}/${item.key}`
                  : ""
              );
            }}
          >
            <RemoveRedEyeIcon />
          </IconButton>
        </Tooltip>,
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        <Tooltip
          disableHoverListener={
            !(item?.killingInfo?.violationMessage && item?.violation)
          }
          key={i}
          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?.poultry?.unitName || "-",
        `${item?.poultry?.userprofile?.fullName ?? "-"} (${
          item?.poultry?.userprofile?.mobile ?? "-"
        })`,
        item?.InteractTypeName,
        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?.archiveDate ? formatTime(item?.archiveDate) : "-",
        item.nowAge || "-",
        item?.quantity?.toLocaleString(),
        item?.increaseQuantity?.toLocaleString() || "-",

        `${item.losses} (%${((item.losses * 100) / item.quantity).toFixed(0)})`,
        `${item?.directLosses?.toLocaleString()} (%${(
          (item.directLosses * 100) /
          item.quantity
        ).toFixed(0)})`,
        `${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?.quantity?.toLocaleString()}`,
        // item?.totalCommitment?.toLocaleString(),

        `%${((item.totalLosses * 100) / item.quantity).toFixed(0)}`,
        `%${((item?.killedQuantity * 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={i}
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "گزارش ",
                  content: (
                    <SimpleTable
                      columns={[
                        "ثبت کننده",
                        "تاریخ ثبت",
                        "تخلف",
                        "متن گزارش",
                        "سند",
                      ]}
                      data={[
                        [
                          item?.violationReporter,
                          formatJustDate(item?.violationReportDate),
                          item?.violation ? "دارد" : "ندارد",
                          item?.violationReport,
                          <ShowImage key={i} src={item?.violationImage} />,
                        ],
                      ]}
                    />
                  ),
                })
              );
            }}
          >
            نمایش
          </Button>
        ) : (
          "بدون گزارش"
        ),
      ];
    });

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

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

  useEffect(() => {
    dispatch(
      cityGetHatchingInfoFull(
        withDate
          ? {
              tab: "archive",
              date1: selectedDate1,
              date2: selectedDate2,
              textValue: textValue,
            }
          : { tab: "archive", textValue: textValue }
      )
    );
  }, [dispatch, withDate, selectedDate1, selectedDate2]);

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

    try {
      const response = await axios.get(
        `poultry_hatching/?archive=true&search=filter&value=${textValue}&role=${getRoleFromUrl()}&key=${userKey}&page=${1}&page_size=${perPage}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }`
      );
      dispatch(
        cityGetHatchingInfoFull(
          withDate
            ? {
                tab: "archive",
                date1: selectedDate1,
                date2: selectedDate2,
                textValue: textValue,
              }
            : { tab: "archive", textValue: textValue }
        )
      );
      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 alignItems="center" justifyContent="center" isDashboard xs={12}>
        <ResponsiveTable
          noPagination
          isDashboard
          title={null}
          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>

      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Grid
          container
          gap={1}
          style={{
            borderStyle: "solid",
            borderWidth: "1px",
            padding: "5px",
            borderRadius: "15px",
            borderColor: "gray",
            justifyContent: "left",
          }}
          alignItems="center"
        >
          <Checkbox
            icon={<ToggleOffOutlinedIcon />}
            checkedIcon={<ToggleOnIcon />}
            checked={withDate}
            onChange={() => setWithDate(!withDate)}
            color="primary"
            size="large"
          />
          <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>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }archive_hatching_excel/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&key=${userKey}${
              withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
            }`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>

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