import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { ChainsActiveChainsOperations } from "../chains-active-chains-operations/ChainsActiveChainsOperations";
import { ChainsSubmitActiveChain } from "../chains-submit-active-chain/ChainsSubmitActiveChain";
import { convertToIranianTime } from "../../../../utils/formatTime";
export const ChainsActiveChains = () => {
  const dispatch = useDispatch();
  const [selectedAge1, setSelectedAge1] = useState(0);
  const [selectedAge2, setSelectedAge2] = useState(0);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const [openNotif] = useContext(AppContext);

  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 fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `poultry_hatching?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&chain=true`
    );

    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);
  };
  const killedNumber = (item) => {
    let killedNumber = "";
    killedNumber = item.quantity - item.losses - item.leftOver;
    return killedNumber;
  };
  useEffect(() => {
    const d = data?.map((item, i) => {
      let lastChange;
      return [
        <ChainsActiveChainsOperations
          key={i}
          item={item}
          updateTable={updateTable}
        />,
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.chainCompany?.name} (${item?.chainCompany?.user.mobile})`,
        item.violation ? "متخلف" : "عادی",
        item.poultry.unitName,
        `${item.poultry.userprofile.fullName} (${item.poultry.userprofile.mobile})`,

        `${item?.poultry?.address.city.name}/${
          item?.poultry?.cityOperator
            ? item?.poultry?.cityOperator
            : "بدون تعاونی"
        }`,
        item?.vetFarm?.vetFarmMobile
          ? `${item?.vetFarm?.vetFarmFullName} (${item?.vetFarm?.vetFarmMobile})`
          : "-",
        item.hall,
        item.period,
        convertToIranianTime(item?.createDate),
        convertToIranianTime(item?.date),
        item.chickenBreed,
        item.age,
        item?.quantity?.toLocaleString(),
        `${item.losses} (%${((item.losses * 100) / item.quantity).toFixed(0)})`,
        `${item?.totalCommitmentQuantity?.toLocaleString()}`,
        `${item?.governmentalQuantity?.toLocaleString()}`,
        `${item?.governmentalKilledQuantity?.toLocaleString()}`,
        `${item?.freeQuantity?.toLocaleString()}`,
        `${item?.freeKilledQuantity?.toLocaleString()}`,
        `${item?.outProvinceKilledQuantity?.toLocaleString()}`,
        `${item?.outProvinceKilledWeight?.toLocaleString()}`,
        item?.chainKilledQuantity?.toLocaleString(),
        item?.chainKilledWeight?.toLocaleString(),
        killedNumber(item)?.toLocaleString() +
          ` (%${((killedNumber(item) * 100) / item.quantity).toFixed(0)})`,
        `${item?.leftOver?.toLocaleString()} (%${(
          (item.leftOver * 100) /
          item.quantity
        ).toFixed(0)})`,

        item?.totalCommitment?.toLocaleString() + " کیلوگرم ",
        item?.governmentalKilledQuantity?.toLocaleString() + " کیلوگرم ",
        item?.freeKilledQuantity?.toLocaleString() + " کیلوگرم ",
        item?.totalAverageKilledWeight?.toLocaleString() + " کیلوگرم ",
        item?.totalKilledWeight?.toLocaleString() + " کیلوگرم ",
        item?.activeKill?.activeKill ? "دارد" : "ندارد",
        item?.activeKill?.countOfRequest ? item.activeKill.countOfRequest : "-",
        (lastChange = item.lastChange
          ? `${item.lastChange.fullName} (${getFaUserRole(
              item.lastChange.role
            )}) در تاریخ ${item.lastChange.date}`
          : "-"),
        (lastChange =
          item.latestHatchingChange &&
          item.latestHatchingChange.date &&
          `${item.latestHatchingChange.fullName} (${getFaUserRole(
            item.latestHatchingChange.role
          )}) در تاریخ ${item.latestHatchingChange.date}`),
        item.latestHatchingChange ? lastChange : "-",
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `poultry_hatching/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&chain=true`
      );

      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(null);
    setSelectedAge2(null);

    try {
      const response = await axios.get(
        `poultry_hatching/?role=${getRoleFromUrl()}&chain=true&search=filter&value=`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const handleSubmitSearchByAge = async (event) => {
    event.preventDefault();

    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `poultry_hatching?role=${getRoleFromUrl()}&age1=${selectedAge1}&age2=${selectedAge2}&chain=true`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const selectAges = Array.from({ length: 75 }, (_, i) => i + 1);

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      paddingTop={2}
      mb={1}
    >
      <Grid
        container
        alignItems="center"
        gap={SPACING.SMALL}
        style={{
          padding: "10px",
          border: "1px solid #bbb",
          borderRadius: "10px",
        }}
      >
        <Typography>زنجیره های فعال</Typography>

        <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>
          <Tooltip title="خروجی اکسل">
            {/* <a
            href={`${axios.defaults.baseURL}0/hatching_excel/`}
            rel="noreferrer"
          > */}
            <Button
              color="success"
              onClick={() => {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                  severity: "success",
                });
                const link = `${
                  axios.defaults.baseURL
                }0/hatching_excel/?role=${getRoleFromUrl()}&key=${userKey}&chain=true`;
                window.location.href = link;
              }}
            >
              <RiFileExcel2Fill size={32} />
            </Button>
            {/* </a> */}
          </Tooltip>
        </form>
      </Grid>
      <Grid
        container
        alignItems="center"
        gap={SPACING.SMALL}
        style={{
          padding: "10px",
          border: "1px solid #bbb",
          borderRadius: "10px",
        }}
      >
        <Grid>
          <Typography variant="caption">جستجو براساس سن:</Typography>
        </Grid>
        <Grid style={{ width: "80px" }}>
          <FormControl fullWidth>
            <InputLabel id="demo-simple-select-label">از سن</InputLabel>
            <Select
              MenuProps={{
                PaperProps: {
                  style: {
                    maxHeight: 200, // Change the maximum height as needed
                    width: 80, // Change the width as needed
                  },
                },
              }}
              labelId="demo-simple-select-label"
              id="demo-simple-select"
              value={selectedAge1}
              label="از سن"
              size="small"
              onChange={(event) => setSelectedAge1(event.target.value)}
            >
              {selectAges.map((age) => (
                <MenuItem key={age} value={age}>
                  {age}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>
        <Grid style={{ width: "80px" }}>
          <FormControl fullWidth>
            <InputLabel id="demo-simple-select-label">تا سن</InputLabel>
            <Select
              MenuProps={{
                PaperProps: {
                  style: {
                    maxHeight: 200, // Change the maximum height as needed
                    width: 80, // Change the width as needed
                  },
                },
              }}
              labelId="demo-simple-select-label"
              id="demo-simple-select"
              value={selectedAge2}
              label="تا سن"
              size="small"
              onChange={(event) => setSelectedAge2(event.target.value)}
            >
              {selectAges.map((age) => (
                <MenuItem key={age} value={age}>
                  {age}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>
        <Button onClick={handleSubmitSearchByAge} endIcon={<RiSearchLine />}>
          جستجو
        </Button>
        <Tooltip title="خروجی اکسل">
          {/* <a
          href={`${axios.defaults.baseURL}hatching_report_from_age_excel/?age1=${selectedAge1}&age2=${selectedAge2}`}
          rel="noreferrer"
        > */}
          <Button
            color="success"
            onClick={() => {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                severity: "success",
              });
              const link = `${axios.defaults.baseURL}hatching_report_from_age_excel/?age1=${selectedAge1}&age2=${selectedAge2}&chain=true`;
              window.location.href = link;
            }}
          >
            <RiFileExcel2Fill size={32} />
          </Button>
          {/* </a> */}
        </Tooltip>
      </Grid>
      <Button onClick={handleRemoveFilter} color="error">
        حذف فیلتر
      </Button>
    </Grid>
  );

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid container xs={12}>
        <Button
          onClick={() => {
            dispatch(
              DRAWER({
                title: "ثبت زنجیره فعال",
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: <ChainsSubmitActiveChain updateTable={updateTable} />,
              })
            );
          }}
          variant="contained"
        >
          ثبت زنجیره فعال
        </Button>
      </Grid>
      {tableTitle}
      <ResponsiveTable
        data={tableData}
        columns={[
          "عملیات",
          "ردیف",
          "شرکت زنجیره",
          "وضعیت",
          "نام فارم",
          "مرغدار",
          "شهر/تعاونی",
          "دامپزشک فارم",
          "سالن",
          "دوره جوجه ریزی",
          "تاریخ ثبت جوجه ریزی",
          "تاریخ جوجه ریزی",
          "نژاد",
          "سن",
          "تعداد جوجه ریزی",
          "تلفات دوره (قطعه)",
          "تعداد کل تعهد دولتی (قطعه)",
          "تعداد کشتار شده دولتی (قطعه)",
          "وزن کشتار شده دولتی",
          "تعداد کشتار شده آزاد (قطعه)",
          "وزن کشتار شده آزاد ",
          "حجم خارج از استان",
          "وزن خارج از استان",
          "حخم کشتار زنجیره (قطعه)",
          "وزن کشتار زنجیره (کیلوگرم)",
          "کشتار شده (قطعه)",
          "مانده در سالن (قطعه)",
          "وزن تعهد دولتی",
          "وزن کشتار دولتی",
          "وزن کشتار آزاد",
          "میانگین وزن کشتار",
          "وزن کل کشتار شده",
          "کشتار فعال",
          "تعداد درخواست کشتار",
          "آخرین تغییر",
          "سازنده جوجه ریزی",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="زنجیره"
      />
    </Grid>
  );
};
