import React, { useContext, useEffect, useState } from "react";
import { Button, TextField } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch } from "react-redux";
import axios from "axios";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import IconButton from "@mui/material/IconButton";
import CreateIcon from "@mui/icons-material/Create";
import { formatJustDate } from "../../../../utils/formatTime";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import CityFileOperations from "../../../file/components/city-file-operations/CityFileOperations";
// import { useNavigate } from "react-router-dom";
// import PlagiarismIcon from "@mui/icons-material/Plagiarism";
// import { ROUTE_PROVINCE_FILE } from "../../../../routes/routes";
import ProvinceCheckRequest from "../../../file/components/province-check-request/ProvinceCheckRequest";
import { RiSearchLine } from "react-icons/ri";

export const ProvinceCityNewRequests = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, 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 navigate = useNavigate();

  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(
      `management_request/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&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.stateProcess === "pending"
          ? "در انتظار تایید شهرستان"
          : "در انتظار تایید استان",
        item.orderCode,
        item?.poultry?.user?.baseOrder,
        formatJustDate(item?.createDate) +
          " " +
          `(${item?.registrar?.fullname} - ${getFaUserRole(
            item?.registrar?.role
          )})`,
        formatJustDate(item?.sendDate),
        item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی",
        `${item?.poultry?.user?.fullname} (${item?.poultry?.user?.mobile})`,
        `${item?.poultry?.unitName}`,
        item?.poultry?.cityOperator,
        item?.poultry?.address?.city?.name,
        formatJustDate(item?.hatching?.hatchingDate),
        item?.hatching?.age,
        item?.IndexWeight,
        item?.quantity.toLocaleString(),
        (item?.quantity * item?.IndexWeight).toLocaleString(),
        <IconButton
          key={i}
          color="primary"
          onClick={() =>
            dispatch(
              DRAWER({
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content:
                  item.stateProcess === "pending" ? (
                    <CityFileOperations
                      file={item}
                      id={item.id}
                      updateTable={updateTable}
                    />
                  ) : (
                    <ProvinceCheckRequest
                      item={item}
                      file={item?.poultryRequest?.process}
                      id={item.id}
                      updateTable={updateTable}
                    />
                  ),
                title: "انجام عملیات تایید/رد",
              })
            )
          }
        >
          <CreateIcon />
        </IconButton>,
        // <IconButton
        //   key={i}
        //   aria-label="delete"
        //   color="primary"
        //   onClick={() =>
        //     navigate(ROUTE_PROVINCE_FILE + item?.poultry?.poultryRequestId)
        //   }
        // >
        //   <PlagiarismIcon />
        // </IconButton>,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `management_request/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&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>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} size="small" />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} size="small" />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </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>
      </Grid>

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