import React, { useEffect, useState, useContext } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { formatTime } from "../../../../utils/formatTime";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { AppContext } from "../../../../contexts/AppContext";
import moment from "moment";
import { DatePicker } from "@mui/x-date-pickers";
import { Button, Checkbox, TextField, Tooltip } from "@mui/material";
import { ProvinceJahadSubmitAllocation } from "../province-jahad-submit-allocation/ProvinceJahadSubmitAllocation";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { ProvinceJahadAllocationOperations } from "../province-jahad-allocation-operations/ProvinceJahadAllocationOperations";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";

export const ProvinceJahadBranDistributionsInventoryAllocations = ({
  inventoryData,
  getDashboardData,
  maxAllow,
  product,
}) => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const dispatch = useDispatch();
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const [textValue, setTextValue] = useState("");

  const [withDate, setWithDate] = useState(false);
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `LiveStock/jahad/live-stock-allocation/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }&page=${page}&page_size=${perPage}&name=${product?.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 getCooperativeState = (item) => {
  //   if (getRoleFromUrl() === "Cooperative") {
  //     return [item?.state === "accepted" ? "تایید شده" : "در انتظار تایید"];
  //   } else {
  //     return [];
  //   }
  // };
  // const getCooperativeStateLabel = () => {
  //   if (getRoleFromUrl() === "Cooperative") {
  //     return ["وضعیت"];
  //   } else {
  //     return [];
  //   }
  // };

  useEffect(() => {
    const d = data?.map((item, i) => {
      const from =
        item?.allocateFrom === "LiveStockProvinceJahad"
          ? item?.jahad?.name
          : item?.union?.name;
      const fromRole = getFaUserRole(item?.allocateFrom);
      const to =
        item?.allocateTo === "Union"
          ? item?.union?.name
          : item?.cooperative?.name;
      const toRole = getFaUserRole(item?.allocateTo);
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.weight?.toLocaleString(),
        // ...getCooperativeState(item),
        `${fromRole} (${from})`,
        `${toRole} (${to})`,
        item?.allocateFrom === "LiveStockProvinceJahad"
          ? item?.jahad?.user?.fullname
          : item?.union?.user?.fullname,
        formatTime(item?.date),
        item?.place,
        item?.description,
        <ProvinceJahadAllocationOperations
          key={i}
          updateTable={updateTable}
          item={item}
          getDashboardData={getDashboardData}
        />,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `LiveStock/jahad/live-stock-allocation/?role=${getRoleFromUrl()}&search=filter&value=${textValue}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }&page=${1}&page_size=${perPage}&name=${product?.key}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  const getColumns = () => {
    if (
      getRoleFromUrl() === "LiveStockProvinceJahad" ||
      getRoleFromUrl() === "Union"
    ) {
      return [
        "ردیف",
        "وزن (کیلوگرم)",
        "مبدا",
        "مقصد",
        "ثبت کننده",
        "تاریخ ثبت",
        "مکان دریافت",
        "توضیحات",
        "عملیات",
      ];
    } else {
      return [
        "ردیف",
        "وزن (کیلوگرم)",
        // ...getCooperativeStateLabel(),
        "مبدا",
        "مقصد",
        "ثبت کننده",
        "تاریخ ثبت",
        "مکان دریافت",
        "توضیحات",
      ];
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        {(getRoleFromUrl() === "LiveStockProvinceJahad" ||
          getRoleFromUrl() === "Union") && (
          <Button
            variant="contained"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: `تخصیص ${product?.label}`,
                  content: (
                    <ProvinceJahadSubmitAllocation
                      updateTable={updateTable}
                      type={"allocate"}
                      productKey={inventoryData?.key}
                      getDashboardData={getDashboardData}
                    />
                  ),
                })
              );
            }}
          >
            تخصیص {product?.label}
          </Button>
        )}

        <Grid
          container
          gap={1}
          style={{
            borderStyle: "solid",
            borderWidth: "1px",
            padding: "5px",
            borderRadius: "15px",
            borderColor: "gray",
            justifyContent: "left",
          }}
          alignItems="center"
        >
          <Checkbox
            icon={<ToggleOffOutlinedIcon />}
            checkedIcon={<ToggleOnIcon />}
            checked={withDate}
            onChange={() => setWithDate(!withDate)}
            color="primary"
            size="large"
          />
          <Grid>
            <DatePicker
              disabled={!withDate}
              label="از تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  style={{ width: "160px" }}
                  {...params}
                />
              )}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              disabled={!withDate}
              label="تا تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  style={{ width: "160px" }}
                  {...params}
                />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        </Grid>
        <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>
        <Tooltip title="خروجی اکسل" placement="left-start">
          <a
            href={`${
              axios.defaults.baseURL
            }LiveStock/jahad/allocation_live_stock_excel/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&key=${userKey}&name=${
              product?.key
            }`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />{" "}
            </Button>
          </a>
        </Tooltip>
      </Grid>

      <ResponsiveTable
        ignoreTextsLength
        data={tableData}
        columns={getColumns()}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={`تخصیصات ${product?.label}`}
      />
    </Grid>
  );
};
