import { Grid } from "../../../../components/grid/Grid";
import React, { useContext, useEffect, useState } from "react";
import {
  Autocomplete,
  Button,
  Checkbox,
  IconButton,
  Tab,
  Tabs,
  TextField,
  Tooltip,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { useParams } from "react-router-dom";
import { formatJustDate } from "../../../../utils/formatTime";
import { nationalInfoGetDashboardService } from "../../services/national-info-get-dashboard-info-service";
import { getSamasatProvinces } from "../../../../utils/getSamasatProvinces";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  ROUTE_ADMINX_ROUTE_NATIONAL_INFO,
  ROUTE_PROVINCE_SUPERVISOR_ROUTE_NATIONAL_INFO,
  ROUTE_SUPER_ADMIN_ROUTE_NATIONAL_INFO,
} from "../../../../routes/routes";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import VisibilityIcon from "@mui/icons-material/Visibility";

export const NationalInfoHatchings = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  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 [selectedProvince, setSelectedProvince] = useState("");

  const { key } = useParams();

  const [dashboardData, setDashboardData] = useState([]);
  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 [value, setValue] = useState("0");

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const getDashboardData = () => {
    dispatch(
      nationalInfoGetDashboardService({
        date1: withDate ? selectedDate1 : null,
        date2: withDate ? selectedDate2 : null,
        search: textValue,
        province: selectedProvince === "همه" ? "" : selectedProvince,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `https://rsibackend.rasadyar.com/app/hatchings/?search=${textValue}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }&page=${page}&page_size=${perPage}&province=${
        key || selectedProvince ? selectedProvince : ""
      }&state=${value === "0" ? "pending" : "archive"}`
    );
    dispatch(LOADING_END());
    getDashboardData();
    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 [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.poultry?.Province || "-",
        item?.poultry?.City || "-",
        item?.poultry?.UnitName,
        `${item?.poultry?.FirstName} ${item?.poultry?.LastName || ""}`,
        item?.RequestCode,
        item?.CertId,
        item?.CapacityFemale?.toLocaleString(),
        formatJustDate(item?.Date),
        Math.floor(item?.Age),
        item?.PedigreeName,
        item?.ChickCountSum?.toLocaleString(),
        item?.Period?.toLocaleString(),
        item?.Evacuation?.toLocaleString(),
        item?.info?.percentHatchingLicense?.toFixed(2),
        item?.LeftOver?.toLocaleString(),
        Math.floor(item?.KillingAve),
        item?.info?.numberLoads?.toLocaleString(),
        item?.info?.loadVolume?.toLocaleString(),
        <Tooltip placement="right" title="جزئیات" key={i}>
          <IconButton
            size="small"
            color="success"
            onClick={() =>
              window.open(
                getRoleFromUrl() === "AdminX"
                  ? `${ROUTE_ADMINX_ROUTE_NATIONAL_INFO}/${item.RequestCode}/${item?.poultry?.UnitName}`
                  : getRoleFromUrl() === "SuperAdmin"
                  ? `${ROUTE_SUPER_ADMIN_ROUTE_NATIONAL_INFO}/${item.RequestCode}/${item?.poultry?.UnitName}`
                  : `${ROUTE_PROVINCE_SUPERVISOR_ROUTE_NATIONAL_INFO}/${item.RequestCode}/${item?.poultry?.UnitName}`,
                "_blank"
              )
            }
          >
            <VisibilityIcon />
          </IconButton>
        </Tooltip>,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `https://rsibackend.rasadyar.com/app/hatchings/?search=${textValue}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }&page=${1}&page_size=${perPage}&province=${
          key || selectedProvince ? selectedProvince : ""
        }&state=${value === "0" ? "pending" : "archive"}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);

      dispatch(LOADING_END());
      getDashboardData();
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const getProvinceList = () => {
    return [{ name: "همه" }, ...getSamasatProvinces()];
  };

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      gap={2}
      mt={2}
    >
      <Grid
        container
        xs={12}
        justifyContent="center"
        alignItems="center"
        gap={2}
      >
        <Tabs value={value} onChange={handleChange}>
          <Tab value="0" label="فعال" />
          <Tab value="1" label="بایگانی شده" />
        </Tabs>
      </Grid>
      <Grid container xs={12} alignItems="center" gap={2}>
        {!key && (
          <Grid minWidth={210}>
            <Autocomplete
              size="small"
              disablePortal
              id="hatching"
              options={getProvinceList().map((i) => {
                return {
                  label: i.name,
                };
              })}
              onChange={(event, value) => {
                if (value.label !== "همه") {
                  setSelectedProvince(value.label);
                } else {
                  setSelectedProvince("");
                }
              }}
              renderInput={(params) => (
                <TextField {...params} label="انتخاب استان" />
              )}
            />
          </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>
        <Grid
          container
          gap={1}
          style={{
            borderStyle: "solid",
            borderWidth: "1px",
            padding: "5px",
            borderRadius: "15px",
            borderColor: "gray",
            justifyContent: "left",
          }}
          alignItems="center"
          sx={{
            width: { xs: "auto", md: "auto" },
          }}
        >
          <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"
                  sx={{ width: { xs: "126px", md: "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"
                  sx={{ width: { xs: "126px", md: "160px" } }}
                  {...params}
                />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        </Grid>
        <Tooltip placement="right" title="دانلود اکسل">
          <IconButton
            size="small"
            color="success"
            component="a"
            href={`https://rsibackend.rasadyar.com/app/all_hatching_excel/?search=${textValue}${
              withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
            }&province=${
              key || selectedProvince ? selectedProvince : ""
            }&state=${value === "0" ? "pending" : "archive"}`}
          >
            <RiFileExcel2Fill size={36} />
          </IconButton>
        </Tooltip>
      </Grid>

      <Grid container mt={2} mb={4} isDashboard gap={3}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد دوره جوجه ریزی",
            "حجم کل جوجه ریزی",
            "تلفات",
            "درصد تلفات",
            "کشتار شده",
            " درصد کشتار شده",
            "میانگین سن کشتار",
            "تعداد بارها",
            "کمترین سن",
            "بیشترین سن",
            "مانده در سالن",
            "درصد مانده در سالن نسبت به جوجه ریزی",
          ]}
          data={[
            [
              dashboardData?.totalHatchingCount?.toLocaleString(),
              dashboardData?.totalHatchingQuantity?.toLocaleString(),
              dashboardData?.totalHatchingEvacuation?.toLocaleString(),
              dashboardData?.totalHatchingEvacuationPercent?.toLocaleString(),
              dashboardData?.totalHatchingKillingQuantity?.toLocaleString(),
              dashboardData?.totalHatchingKillingQuantityPercent?.toLocaleString(),
              Math.floor(dashboardData?.totalHatchingKillingAge),
              dashboardData?.totalHatchingBars?.toLocaleString(),
              Math.floor(dashboardData?.leastAge),
              Math.floor(dashboardData?.mostAge),
              dashboardData?.totalHatchingLeftOver?.toLocaleString(),
              dashboardData?.totalHatchingLeftOverPercent?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات کل جوجه ریزی ها"}
        />
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد دوره جوجه ریزی",
            "حجم کل جوجه ریزی",
            "تلفات",
            "درصد تلفات",
            "کشتار شده",
            "درصد کشتار شده",
            "میانگین سن کشتار",
            "تعداد بارها",
            "حجم جوجه ریزی فعال",
            "کمترین سن",
            "بیشترین سن",
            "مانده در سالن",
            "درصد مانده در سالن",
            "مانده در سالن آماده به کشتار",
            "درصد مانده در سالن آماده به کشتار",
          ]}
          data={[
            [
              dashboardData?.totalActiveHatchingCount?.toLocaleString(),
              dashboardData?.totalActiveHatchingQuantity?.toLocaleString(),
              dashboardData?.totalActiveHatchingEvacuation?.toLocaleString(),
              dashboardData?.totalActiveHatchingEvacuationPercent?.toLocaleString(),
              dashboardData?.totalActiveHatchingKillingQuantity?.toLocaleString(),
              dashboardData?.totalActiveHatchingKillingQuantityPercent?.toLocaleString(),
              Math.floor(dashboardData?.totalActiveHatchingKillingAge),
              dashboardData?.totalActiveHatchingBars?.toLocaleString(),
              // dashboardData?.totalActiveHatchingCount?.toLocaleString(),
              dashboardData?.totalActiveHatchingQuantity?.toLocaleString(),
              Math.floor(dashboardData?.leastAge),
              Math.floor(dashboardData?.mostAge),
              dashboardData?.totalActiveHatchingLeftOver?.toLocaleString(),
              dashboardData?.totalActiveHatchingLeftOverPercent?.toLocaleString(),
              dashboardData?.totalReadyActiveHatchingLeftOver?.toLocaleString(),
              dashboardData?.totalReadyHatchingLeftOverPercent?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات جوجه ریزی های فعال"}
          customColors={[{ rest: true, color: "#6262c4" }]}
        />
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "استان",
          "شهرستان",
          "نام واحد",
          "نام مالک",
          "شماره مجوز",
          "شماره گواهی بهداشتی",
          "ظرفیت",
          "تاریخ جوجه ریزی",
          "سن گله",
          "نژاد",
          "تعداد جوجه ریزی",
          "دوره جوجه ریزی",
          "مجموع تلفات",
          "درصد جوجه ریزی به مجوز",
          "مانده در سالن",
          "میانگین سن کشتار",
          "تعداد بارها",
          "حجم بارها",
          "جزئیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={
          value === "0"
            ? `پایش جوجه ریزی  ${key || ""}`
            : `بایگانی جوجه ریزی  ${key || ""}`
        }
      />
    </Grid>
  );
};
