import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import moment from "moment";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import EditIcon from "@mui/icons-material/Edit";

import {
  DRAWER,
  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 { ChainsCompaniesSubmit } from "../chains-companies-submit/ChainsCompaniesSubmit";

export const ProvinceChainsCompanies = () => {
  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);
  }, [setSelectedDate1, setSelectedDate2]);

  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 handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const isAvalableEdit = () => {
    if (
      getRoleFromUrl() === "AdminX" ||
      getRoleFromUrl() === "SuperAdmin" ||
      getRoleFromUrl() === "ProvinceOperator"
    ) {
      return false;
    } else {
      return true;
    }
  };

  const fetchApiData = async (page = 1) => {
    try {
      dispatch(LOADING_START());
      const response = await axios.get(
        `chain-company/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}&state=total_companies`
      );
      dispatch(LOADING_END());
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      dispatch(LOADING_END());
      console.error("Error fetching data:", error);
    }
  };

  const handlePageChange = (newPage) => {
    setPage(newPage);
    fetchApiData(newPage);
  };

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

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

  useEffect(() => {
    const formattedData = data?.map((item, i) => [
      page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
      item.name,
      item.user.firstName,
      item.user.lastName,
      item.user.mobile,
      item.province,
      item.city,
      item.address,
      item.postalCode,
      item.requestsInfo?.numberOfRequests?.toLocaleString(),
      item.requestsInfo?.totalQuantity?.toLocaleString(),
      item.requestsInfo?.totalWeight?.toLocaleString(),
      <Tooltip title="ویرایش اطلاعات" placement="left" key={i}>
        <IconButton
          disabled={isAvalableEdit()}
          color="primary"
          onClick={() =>
            dispatch(
              DRAWER({
                title: "ویرایش شرکت زنجیره",
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: <ChainsCompaniesSubmit item={item} />,
              })
            )
          }
        >
          <EditIcon />
        </IconButton>
      </Tooltip>,
    ]);
    setTableData(formattedData);
  }, [data, page, perPage]);

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

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid container xs={12}>
        {(getRoleFromUrl() === "ProvinceOperator" ||
          getRoleFromUrl() === "SuperAdmin") && (
          <Button
            onClick={() =>
              dispatch(
                DRAWER({
                  title: "ثبت شرکت زنجیره",
                  right: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  content: <ChainsCompaniesSubmit />,
                })
              )
            }
            variant="contained"
          >
            ثبت شرکت زنجیره
          </Button>
        )}
      </Grid>

      <Grid
        container
        xs={12}
        justifyContent="center"
        alignItems="center"
        gap={2}
      >
        <Grid
          container
          alignItems="center"
          justifyContent="center"
          gap={2}
          paddingTop={2}
          mb={1}
          width="100%"
        >
          <Typography>خریداران</Typography>
          <Grid container alignItems="center" gap={2}>
            <form onSubmit={handleSubmit}>
              <TextField
                id="outlined-basic"
                size="small"
                autoComplete="off"
                label="جستجو"
                variant="outlined"
                style={{ width: 250 }}
                onChange={handleTextChange}
              />
              <Button type="submit" endIcon={<RiSearchLine />}>
                جستجو
              </Button>
            </form>
            <Grid>
              <Tooltip title="خروجی اکسل شرکت های زنجیره">
                <a
                  href={`${
                    axios.defaults.baseURL
                  }chain_company_buyers_excel/?role=${getRoleFromUrl()}&key=${userKey}&search=filter&value=${textValue}`}
                  rel="noreferrer"
                >
                  <Button color="success">
                    <RiFileExcel2Fill size={32} />
                  </Button>
                </a>
              </Tooltip>
            </Grid>
          </Grid>
        </Grid>
      </Grid>

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