import { Button, TextField, Tooltip, Typography } from "@mui/material";
import axios from "axios";
import { useEffect, useState } from "react";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { CityHatchingsArchiveOperations } from "../../../city/components/city-hatchings-archive-operations/CityHatchingsArchiveOperations";
import { formatTime } from "../../../../utils/formatTime";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { useSelector } from "react-redux";

const OperationsCell = ({ item, updateArchive, readOnly }) => (
  <CityHatchingsArchiveOperations
    item={item}
    updateArchive={updateArchive}
    readOnly={readOnly}
  />
);

export const ChainsArchiveChains = ({ readOnly }) => {
  readOnly = readOnly || false;
  const [data, setData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [page, setPage] = useState(1);

  const [textValue, setTextValue] = useState("");
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

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

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

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

  const handlePerRowsChange = (newPerPage) => {
    setPerPage(Number(newPerPage));
    setPage(1);
  };

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

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

  const columns = [
    "عملیات",
    "ردیف",
    "شرکت زنجیره",
    "وضعیت",
    "نام فارم",
    "مرغدار",
    "شهر/تعاونی",
    "دامپزشک فارم",
    "سالن",
    "دوره جوجه ریزی",
    "تاریخ ثبت جوجه ریزی",
    "تاریخ جوجه ریزی",
    "نژاد",
    "سن",
    "تعداد جوجه ریزی",
    "تلفات دوره",
    "حجم خارج از استان",
    "وزن کشتار شده دولتی",
    "وزن کشتار شده آزاد ",
    "وزن خارج از استان",
    "حخم کشتار زنجیره (قطعه)",
    "وزن کشتار زنجیره (کیلوگرم)",
    "کشتار شده",
    "مانده در سالن",
    "کشتار فعال",
    "تعداد درخواست کشتار",
    "آخرین تغییر",
  ];

  useEffect(() => {
    if (!data || !Array.isArray(data)) {
      setTableData([]);
      return;
    }

    const transformedData = data.map((item, i) => {
      const killedNumber = item?.quantity - item?.losses - item?.leftOver;
      const lastChange =
        item?.lastChange &&
        item?.lastChange?.date &&
        `${item?.lastChange?.fullName} (${getFaUserRole(
          item?.lastChange?.role
        )}) در تاریخ ${formatTime(item?.lastChange?.date)}`;

      return [
        <OperationsCell
          key={`operations-${item?.key || i}`}
          item={item}
          updateArchive={(pageNum) => fetchApiData(pageNum || page, textValue)}
          readOnly={readOnly}
        />,
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.chainCompany?.name && item?.chainCompany?.user?.mobile
          ? `${item.chainCompany.name} (${item.chainCompany.user.mobile})`
          : "-",
        <Typography
          key={`status-${item?.key || i}`}
          variant="body2"
          color={item?.violation ? "error" : "black"}
        >
          {item?.violation ? "متخلف" : "عادی"}
        </Typography>,
        item?.poultry?.unitName || "-",
        item?.poultry?.userprofile?.fullName &&
        item?.poultry?.userprofile?.mobile
          ? `${item.poultry.userprofile.fullName} (${item.poultry.userprofile.mobile})`
          : "-",
        item?.poultry?.address?.city?.name
          ? `${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?.chickenBreed || "-",
        item?.age || "-",
        item?.quantity ? item.quantity.toLocaleString() : "-",
        item?.losses && item?.quantity
          ? `${item.losses} (%${((item.losses * 100) / item.quantity).toFixed(
              0
            )})`
          : "-",
        item?.outProvinceKilledQuantity
          ? item.outProvinceKilledQuantity.toLocaleString()
          : "-",
        item?.governmentalKilledQuantity
          ? item.governmentalKilledQuantity.toLocaleString()
          : "-",
        item?.freeKilledQuantity
          ? item.freeKilledQuantity.toLocaleString()
          : "-",
        item?.outProvinceKilledWeight
          ? item.outProvinceKilledWeight.toLocaleString()
          : "-",
        item?.chainKilledQuantity
          ? item.chainKilledQuantity.toLocaleString()
          : "-",
        item?.chainKilledWeight ? item.chainKilledWeight.toLocaleString() : "-",
        item?.quantity && killedNumber !== undefined
          ? `${killedNumber.toLocaleString()} (%${(
              (killedNumber * 100) /
              item.quantity
            ).toFixed(0)})`
          : "-",
        item?.leftOver && item?.quantity
          ? `${item.leftOver.toLocaleString()} (%${(
              (item.leftOver * 100) /
              item.quantity
            ).toFixed(0)})`
          : "-",
        item?.activeKill?.activeKill ? "دارد" : "ندارد",
        item?.activeKill?.countOfRequest || "-",
        lastChange || "-",
      ];
    });

    setTableData(transformedData);
  }, [data, page, perPage, textValue, readOnly]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    setPage(1);
    fetchApiData(1, textValue);
  };

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      paddingTop={2}
      mb={1}
    >
      <Grid container alignItems="center" gap={SPACING.SMALL}>
        <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
              }archive_hatching_excel/?chain=true&key=${userKey}&role=${getRoleFromUrl()}`}
              rel="noreferrer"
            >
              <Button color="success">
                <RiFileExcel2Fill size={32} />
              </Button>
            </a>
          </Tooltip>
        </form>
      </Grid>
    </Grid>
  );

  return (
    <Grid alignItems="center" justifyContent="center" xs={12}>
      <ResponsiveTable
        title={tableTitle}
        columns={columns}
        data={tableData}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePageChange={handlePageChange}
        handlePerRowsChange={handlePerRowsChange}
      />
    </Grid>
  );
};
