import {
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import React, { useContext, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import axios from "axios";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatTime } from "../../../../utils/formatTime";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { PageTable } from "../../../../components/page-table/PageTable";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";

export const ChainCompanyActiveChains = () => {
  const [selectedAge1, setSelectedAge1] = useState(0);
  const [selectedAge2, setSelectedAge2] = useState(0);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

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

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

  const [openNotif] = useContext(AppContext);

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

  const fetchApiData = async (page, textValue) => {
    setLoading(true);
    let response;
    if (textValue) {
      response = await axios.get(
        `poultry_hatching?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&chain=true`
      );
    } else if (selectedAge1 && selectedAge2) {
      response = await axios.get(
        `poultry_hatching?role=${getRoleFromUrl()}&age1=${selectedAge1}&age2=${selectedAge2}&page=${page}&page_size=${perPage}&chain=true`
      );
    } else {
      response = await axios.get(
        `poultry_hatching/?role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&chain=true`
      );
    }
    setData(response.data.results);
    setTotalRows(response.data.count);
    setLoading(false);
  };

  const handlePageChange = (page) => {
    fetchApiData(page, textValue);
  };

  //   const updateTable = () => {
  //     fetchApiData(1);
  //   };

  const handlePerRowsChange = async (newPerPage, page) => {
    setLoading(true);
    let response;
    if (textValue) {
      response = await axios.get(
        `poultry_hatching?search=filter&value=${textValue}&page=${page}&page_size=${newPerPage}&search=filter&value=${textValue}&chain=true`
      );
    } else if (selectedAge1 && selectedAge2) {
      response = await axios.get(
        `poultry_hatching?role=${getRoleFromUrl()}&age1=${selectedAge1}&age2=${selectedAge2}&page=${page}&page_size=${perPage}&chain=true`
      );
    } else {
      response = await axios.get(
        `poultry_hatching/?role=${getRoleFromUrl()}&page=${page}&page_size=${newPerPage}&chain=true`
      );
    }

    setData(response.data.results);
    setTotalRows(response.data.count);
    setPerPage(newPerPage);

    setLoading(false);
  };
  const handleSubmit = async (event) => {
    event.preventDefault();
    setLoading(true);

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

  const handleRemoveFilter = async (event) => {
    event.preventDefault();
    setSelectedAge1(null);
    setSelectedAge2(null);
    setLoading(true);

    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);
    } finally {
      setLoading(false);
    }
  };

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

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

  let columns = [
    //   {
    //     name: "عملیات",
    //     selector: (item) => (
    //       <ChainsActiveChainsOperations item={item} updateTable={updateTable} />
    //     ),
    //     sortable: false,
    //     wrap: true,
    //     allowOverflow: true,
    //     center: true,
    //     width: "80px",
    //   },
    {
      name: "ردیف",
      selector: (item, i) => {
        return i + 1;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "30px",
    },
    {
      name: "شرکت زنجیره",
      selector: (item, i) => {
        return `${item?.chainCompany?.name} (${item?.chainCompany?.user.mobile})`;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "وضعیت",
      selector: (item, i) => {
        return (
          <Typography
            variant="body2"
            color={item.violation ? "error" : "black"}
          >
            {item.violation ? "متخلف" : "عادی"}
          </Typography>
        );
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "60px",
    },
    {
      name: "نام فارم",
      selector: (row) => row.poultry.unitName,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "مرغدار",
      selector: (item) =>
        `${item.poultry.userprofile.fullName} (${item.poultry.userprofile.mobile})`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "شهر/تعاونی",
      selector: (item) =>
        `${item?.poultry?.address.city.name}/${
          item?.poultry?.cityOperator
            ? item?.poultry?.cityOperator
            : "بدون تعاونی"
        }`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "دامپزشک فارم",
      selector: (item) =>
        item?.vetFarm?.vetFarmMobile
          ? `${item?.vetFarm?.vetFarmFullName} (${item?.vetFarm?.vetFarmMobile})`
          : "-",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "سالن",
      selector: (item) => item.hall,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "60px",
    },
    {
      name: "دوره جوجه ریزی",
      selector: (item) => item.period,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "تاریخ ثبت جوجه ریزی",
      selector: (item) => formatTime(item?.createDate),
      sortable: false,
      wrap: false,
      allowOverflow: true,
      center: true,
      width: "100px",
    },
    {
      name: "تاریخ جوجه ریزی",
      selector: (item) => formatTime(item?.date),
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "100px",
    },
    {
      name: "نژاد",
      selector: (item) => item.chickenBreed,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "سن",
      selector: (row) => row.age,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "60px",
    },
    {
      name: "تعداد جوجه ریزی",
      selector: (item) => item?.quantity?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "تلفات دوره (قطعه)",
      selector: (item) =>
        `${item.losses} (%${((item.losses * 100) / item.quantity).toFixed(0)})`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "تعداد کل تعهد دولتی (قطعه)",
      selector: (item) => `${item?.totalCommitmentQuantity?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "تعداد کشتار شده دولتی (قطعه)",
      selector: (item) => `${item?.governmentalQuantity?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "وزن کشتار شده دولتی",
      selector: (item) =>
        `${item?.governmentalKilledQuantity?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "تعداد کشتار شده آزاد (قطعه)",
      selector: (item) => `${item?.freeQuantity?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "وزن کشتار شده آزاد ",
      selector: (item) => `${item?.freeKilledQuantity?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "حجم خارج از استان",
      selector: (item) =>
        `${item?.outProvinceKilledQuantity?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "وزن خارج از استان",
      selector: (item) => `${item?.outProvinceKilledWeight?.toLocaleString()}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "کشتار شده (قطعه)",
      selector: (item) => {
        return (
          killedNumber(item)?.toLocaleString() +
          ` (%${((killedNumber(item) * 100) / item.quantity).toFixed(0)})`
        );
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "مانده در سالن (قطعه)",
      selector: (item) =>
        `${item?.leftOver?.toLocaleString()} (%${(
          (item.leftOver * 100) /
          item.quantity
        ).toFixed(0)})`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "90px",
    },
    {
      name: "وزن تعهد دولتی",
      selector: (item) => item?.totalCommitment?.toLocaleString() + " کیلوگرم ",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "وزن کشتار دولتی",
      selector: (item) =>
        item?.governmentalKilledQuantity?.toLocaleString() + " کیلوگرم ",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "وزن کشتار آزاد",
      selector: (item) =>
        item?.freeKilledQuantity?.toLocaleString() + " کیلوگرم ",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "میانگین وزن کشتار",
      selector: (item) =>
        item?.totalAverageKilledWeight?.toLocaleString() + " کیلوگرم ",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "وزن کل کشتار شده",
      selector: (item) =>
        item?.totalKilledWeight?.toLocaleString() + " کیلوگرم ",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "کشتار فعال",
      selector: (row) => (row?.activeKill?.activeKill ? "دارد" : "ندارد"),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "تعداد درخواست کشتار",
      selector: (item) =>
        item?.activeKill?.countOfRequest ? item.activeKill.countOfRequest : "-",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "آخرین تغییر",
      selector: (item) => {
        const lastChange =
          item.lastChange &&
          item.lastChange.date &&
          `${item.lastChange.fullName} (${getFaUserRole(
            item.lastChange.role
          )}) در تاریخ ${formatTime(item.lastChange.date)}`;
        return item.lastChange ? lastChange : "-";
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "سازنده جوجه ریزی",
      selector: (item) => {
        const lastChange =
          item.latestHatchingChange &&
          item.latestHatchingChange.date &&
          `${item.latestHatchingChange.fullName} (${getFaUserRole(
            item.latestHatchingChange.role
          )}) در تاریخ ${formatTime(item.latestHatchingChange.date)}`;
        return item.latestHatchingChange ? lastChange : "-";
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
  ];

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

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      paddingTop={2}
      mb={1}
      width="100%"
      mt={2}
    >
      <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}>جستجو</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}>
      {/* <Button
          onClick={() => {
            dispatch(
              DRAWER({
                title: "ثبت زنجیره فعال",
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: <ChainsSubmitActiveChain updateTable={updateTable} />,
              })
            );
          }}
          variant="contained"
        >
          ثبت زنجیره فعال
        </Button> */}

      <Grid container xs={12} justifyContent="center" mt={2}>
        <PageTable
          title={tableTitle}
          columns={columns}
          data={data}
          progressPending={loading}
          pagination
          paginationServer
          paginationTotalRows={totalRows}
          onChangeRowsPerPage={handlePerRowsChange}
          onChangePage={handlePageChange}
        />
      </Grid>
    </Grid>
  );
};
