import React, { useEffect, useState } from "react";
import { Button, IconButton, TextField, Tooltip } from "@mui/material";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { useDispatch, useSelector } from "react-redux";
import { ProvinceJahadCooperativesOperations } from "../province-jahad-cooperatives-operations/ProvinceJahadCooperativesOperations";
import { ProvinceJahadEditCooperative } from "../province-jahad-edit-cooperative/ProvinceJahadEditCooperative";
import TabletAndroidIcon from "@mui/icons-material/TabletAndroid";
import { ProvinceJahadCooperativesModal } from "../province-jahad-cooperatives-modal/ProvinceJahadCooperativesModal";

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

  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  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(
      `/LiveStock/cooperative/cooperative-views/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`
    );

    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?.user.fullname,
        item?.address?.province?.name,
        item?.address?.city?.name,
        item?.user.mobile,
        item?.nationalId,
        item?.account || "-",
        item?.user?.password || "-",
        <Tooltip placement="left" title="لیست دستگاه POS" key={i}>
          <IconButton
            aria-label="delete"
            variant="outlined"
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: `لیست دستگاه‌های POS تعاونی ${item?.name}`,
                  content: <ProvinceJahadCooperativesModal item={item} />,
                })
              );
            }}
          >
            <TabletAndroidIcon />
          </IconButton>
        </Tooltip>,
        <ProvinceJahadCooperativesOperations
          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(
        `/LiveStock/cooperative/cooperative-views/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`
      );
      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({
                title: "ایجاد تعاونی",
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: (
                  <ProvinceJahadEditCooperative updateTable={updateTable} />
                ),
              })
            );
          }}
        >
          ایجاد تعاونی
        </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>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }live-stock-cooperatives-excel/?role=${getRoleFromUrl()}&key=${userKey}`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "نام تعاونی",
          "کاربر",
          "استان",
          "شهر",
          "موبایل",
          "کد ملی",
          "شماره شبا",
          "کلمه عبور",
          "POS",
          "عملیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="تعاونی ها "
      />
    </Grid>
  );
};
