import React, { useEffect, useState } from "react";
import { Button, TextField } from "@mui/material";
import { useDispatch } from "react-redux";
import axios from "axios";
import { RiSearchLine } from "react-icons/ri";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { formatJustDate } from "../../../../utils/formatTime";
import { useParams } from "react-router-dom";

export const VisorStaticsPredictionDetails = () => {
  const { key, date } = useParams();
  const dispatch = useDispatch();
  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 fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `poultry_hatching_prediction/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&hatching_list=${key}`
    );
    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 [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.poultry?.unitName,
        item?.poultry?.fullname || "-",
        item?.poultry?.killingAveAge?.toLocaleString(),
        item?.poultry?.realKillingAveWeight?.toLocaleString(),
        item?.period?.toLocaleString(),
        formatJustDate(item?.date),
        item?.quantity?.toLocaleString(),
        item?.generalInfo?.age?.toLocaleString(),
        item?.chickenBreed || "-",
        item?.generalInfo?.totalQuantity?.toLocaleString(),
        item?.generalInfo?.totalWeight?.toLocaleString(),
        item?.generalInfo?.provinceKillRequests?.toLocaleString(),
        item?.generalInfo?.provinceKillRequestsQuantity?.toLocaleString(),
        item?.generalInfo?.provinceKillRequestsWeight?.toLocaleString(),
        item?.leftOver?.toLocaleString(),
        Math.round(
          item?.poultry?.realKillingAveWeight * item?.leftOver
        ).toLocaleString(),
        Math.round(
          item?.poultry?.realKillingAveWeight * item?.leftOver * 0.75
        ).toLocaleString(),
      ];
    });

    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_prediction/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&page=${1}&page_size=${perPage}&hatching_list=${key}`
      );
      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}
      mt={2}
    >
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <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>

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