import React, { useEffect, useState } from "react";
import { Button, TextField } from "@mui/material";

import axios from "axios";
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 { useParams } from "react-router-dom";
import { useDispatch } from "react-redux";
import { ProvinceStewardShowColdHousesListOperations } from "../province-steward-show-cold-houses-list-operations/ProvinceStewardShowColdHousesListOperations";
import { ProvinceColdHousesListAddColdHouse } from "../province-cold-houses-list-add-cold-house/ProvinceColdHousesListAddColdHouse";
import { RiSearchLine } from "react-icons/ri";

export const ProvinceStewardShowColdHousesList = () => {
  const dispatch = useDispatch();
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const { key, name, type } = useParams();

  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(
      `cold-house-for-province/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}${
        type === "steward" ? `&type=Steward&steward_key=${key}` : ""
      }${type === "killhouse" ? `&type=KillHouse&kill_house_key=${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?.name,
        item?.city,
        item?.address,
        item?.totalInputWeight?.toLocaleString(),
        item?.totalAllocatedWeight?.toLocaleString(),
        item?.totalRemainWeight?.toLocaleString(),
        item?.active ? "فعال" : "غیر فعال",
        item?.broadcast ? "دارد" : "ندارد",
        item?.relocate ? "دارد" : "ندارد",
        item?.capacity,
        <ProvinceStewardShowColdHousesListOperations
          key={i}
          item={item}
          updateTable={updateTable}
        />,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `cold-house-for-province/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&page=${1}&page_size=${perPage}${
          type === "steward" ? `&type=Steward&steward_key=${key}` : ""
        }${type === "killhouse" ? `&type=KillHouse&kill_house_key=${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}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Button
          variant="contained"
          onClick={() => {
            dispatch(
              DRAWER({
                right: true,
                title: "افزودن سردخانه",
                content: (
                  <ProvinceColdHousesListAddColdHouse
                    updateTable={updateTable}
                    stewardKey={key}
                    killhouseKey={key}
                  />
                ),
              })
            );
          }}
        >
          افزودن سردخانه
        </Button>

        <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={`مشاهده سردخانه های ${name}`}
      />
    </Grid>
  );
};
