import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import moment from "moment";
import { useDispatch } from "react-redux";
import axios from "axios";
import { RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { AppContext } from "../../../../contexts/AppContext";
import AddIcon from "@mui/icons-material/Add";
import { ProvincePoultryScienceExpertsAddPoultry } from "../province-poultry-science-experts-add-poultry/ProvincePoultryScienceExpertsAddPoultry";
import { provincePoultryScienceExpertsAllPoultryService } from "../../services/province-poultry-science-experts-add-poultry-service";

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

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const [data, setData] = useState([]);
  const [poultryExperts, setPoultryExperts] = 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_science/?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 getExperts = () => {
    dispatch(provincePoultryScienceExpertsAllPoultryService()).then((r) => {
      setPoultryExperts(r.payload.data);
    });
  };

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

  useEffect(() => {
    updateTable();
  }, [dispatch]);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.user?.fullname,
        item?.user?.mobile,
        <Typography key={i} variant="caption">
          {item?.poultry?.length
            ? item?.poultry
                ?.map(
                  (opt, idx) =>
                    `${opt.unitName} (${opt.user?.fullname} - ${opt.user?.mobile})`
                )
                ?.join(" - ")
            : "-"}
        </Typography>,
        <Tooltip title="مدیریت مرغدار زیر مجموعه" key={i} placement="right">
          <IconButton
            disabled={!poultryExperts?.length}
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "افزودن مرغدار زیرمجموعه",
                  content: (
                    <ProvincePoultryScienceExpertsAddPoultry
                      updateTable={updateTable}
                      item={item}
                      poultryExperts={poultryExperts}
                    />
                  ),
                })
              );
            }}
          >
            <AddIcon />
          </IconButton>
        </Tooltip>,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `poultry_science/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&page=${1}&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}
      >
        <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="کارشناسان علوم دامی"
      />
    </Grid>
  );
};
