import { Button, TextField, Typography } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import PlagiarismIcon from "@mui/icons-material/Plagiarism";
// import { ROUTE_CITY_FILE } from "../../../../routes/routes";
// import { avicultureGetRequests } from "../../../aviculture/services/aviculture-requests";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { AppContext } from "../../../../contexts/AppContext";
import { PageTable } from "../../../../components/page-table/PageTable";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import axios from "axios";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { formatJustDate } from "../../../../utils/formatTime";
import { IconButton } from "@mui/material";
import { ROUTE_CITY_FILE } from "../../../../routes/routes";
import { useNavigate } from "react-router-dom";
import { RiSearchLine } from "react-icons/ri";

export const CityActiveRequests = () => {
  const navigate = useNavigate();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  // page table
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);

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

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

  const fetchApiData = async (page, textValue) => {
    setLoading(true);
    let response = await axios.get(
      `Poultry_Request/?state=accepted&date1=${selectedDate1}&date2=${selectedDate2}&search=filter&value=${
        textValue ? textValue : ""
      }&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`
    );
    setData(response.data.results);
    setTotalRows(response.data.count);
    setLoading(false);
  };

  const handlePageChange = (page) => {
    fetchApiData(page, textValue);
  };

  const handlePerRowsChange = async (newPerPage, page) => {
    setLoading(true);
    let response = await axios.get(
      `Poultry_Request/?state=accepted&date1=${selectedDate1}&date2=${selectedDate2}&search=filter&value=${
        textValue ? textValue : ""
      }&page=${page}&page_size=${newPerPage}`
    );

    setData(response.data.results);
    setTotalRows(response.data.count);
    setPerPage(newPerPage);

    setLoading(false);
  };

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    setLoading(true);

    try {
      const response = await axios.get(
        `Poultry_Request/?state=accepted&date1=${selectedDate1}&date2=${selectedDate2}&role=${getRoleFromUrl()}&search=filter&value=${
          textValue ? textValue : ""
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      name: "ردیف",
      selector: (item, i) => {
        return i + 1;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "40px",
    },
    {
      name: "وضعیت",
      selector: (item) => (
        <Typography
          variant="body2"
          color={item.provinceState === "rejected" ? "error" : "promary"}
        >
          {item.provinceState === "pending"
            ? "درانتظار تایید استان"
            : item.provinceState === "accepted"
            ? "تایید شده توسط استان"
            : "رد شده"}
        </Typography>
      ),
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "کدسفارش",
      selector: (item) => item.orderCode,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "تاریخ ثبت درخواست",
      selector: (item) => formatJustDate(item.createDate),
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "نوع کشتار",
      selector: (item) => {
        return item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی";
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "80px",
    },
    {
      name: "تاریخ کشتار",
      selector: (item) => formatJustDate(item.sendDate),
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "مرغداری",
      selector: (item) =>
        `${item?.poultry?.unitName} (${item?.poultry?.user?.mobile})`,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "شهر",
      selector: (item) => item?.poultry?.address?.city?.name,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "استان",
      selector: (item) => item?.poultry?.address?.province?.name,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "تاریخ جوجه ریزی",
      selector: (item) => formatJustDate(item.hatching.hatchingDate),
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "سن",
      selector: (item) => item.hatching.age,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "تعداد (قطعه)",
      selector: (item) => item?.quantity,
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "مشاهده",
      selector: (item) => {
        return (
          <IconButton
            aria-label="delete"
            color="primary"
            onClick={() => navigate(ROUTE_CITY_FILE + item?.id)}
          >
            <PlagiarismIcon />
          </IconButton>
        );
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
  ];

  // useEffect(() => {
  //   dispatch(LOADING_START());
  //   dispatch(avicultureGetRequests({ selectedDate1, selectedDate2 })).then(
  //     (r) => {
  //       dispatch(LOADING_END());
  //     }
  //   );
  // }, [selectedDate1, selectedDate2]);

  // useEffect(() => {
  //   const filteredData = avicultureRequests?.filter(
  //     (item, i) => item.stateProcess === "pending"
  //   );
  //   const d = filteredData?.map((item, i) => {
  //     return [
  //       i + 1,
  //       item.orderCode,
  //       item.poultry.userprofile.baseOrder,
  //       formatJustDate(item.createDate),
  //       formatJustDate(item.sendDate),
  //       item?.process?.poultry?.poultryName,
  //       item?.process?.poultry?.poultryMobile,
  //       item?.process?.poultry?.poultryCity,
  //       item?.process?.poultry?.poultryProvince,
  //       formatJustDate(item.hatching.date),
  //       item?.process?.poultry?.age,
  //       item?.process?.poultry?.poultryQuantity,
  //       <IconButton
  //         key={i}
  //         color="primary"
  //         onClick={() =>
  //           dispatch(
  //             DRAWER({
  //               right: !(window.innerWidth <= 600),
  //               bottom: window.innerWidth <= 600,
  //               content: (
  //                 <CityFileOperations id={item.id} file={item?.process} />
  //               ),
  //               title: "انجام عملیات شهرستان",
  //             })
  //           )
  //         }
  //       >
  //         <CreateIcon />
  //       </IconButton>,
  //       <IconButton
  //         key={i}
  //         aria-label="delete"
  //         color="primary"
  //         onClick={() =>
  //           navigate(ROUTE_CITY_FILE + item?.process?.poultry?.poultryRequestId)
  //         }
  //       >
  //         <PlagiarismIcon />
  //       </IconButton>,
  //     ];
  //   });

  //   setDataTable(d);
  // }, [avicultureRequests]);

  return (
    <>
      {/* <AdvancedTable
        name={
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <Grid container gap={SPACING.TINY}>
              <Typography>درخواست های جدید فروش اتحادیه</Typography>
            </Grid>
            <Grid container gap={SPACING.SMALL}>
              <Grid>
                <DatePicker
                  label="از تاریخ"
                  id="date"
                  renderInput={(params) => (
                    <TextField style={{ width: "160px" }} {...params} />
                  )}
                  value={selectedDate1}
                  onChange={(e) => {
                    setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                  }}
                />
              </Grid>
              <Grid>
                <DatePicker
                  label="تا تاریخ"
                  id="date"
                  renderInput={(params) => (
                    <TextField style={{ width: "160px" }} {...params} />
                  )}
                  value={selectedDate2}
                  onChange={(e) => {
                    setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                  }}
                />
              </Grid>
            </Grid>
          </Grid>
        }
        columns={columnsName}
        data={dataTable}
      /> */}

      <Grid alignItems="center" justifyContent="center" mt={4}>
        <PageTable
          title={
            <Grid
              container
              alignItems="center"
              justifyContent="space-between"
              gap={2}
              paddingTop={2}
              mb={1}
            >
              <Grid container alignItems="center" gap={SPACING.SMALL}>
                <Typography>درخواست های فعال</Typography>
                <Grid container gap={SPACING.SMALL}>
                  <Grid>
                    <DatePicker
                      label="از تاریخ"
                      id="date"
                      renderInput={(params) => (
                        <TextField style={{ width: "160px" }} {...params} />
                      )}
                      value={selectedDate1}
                      onChange={(e) => {
                        setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                      }}
                    />
                  </Grid>
                  <Grid>
                    <DatePicker
                      label="تا تاریخ"
                      id="date"
                      renderInput={(params) => (
                        <TextField style={{ width: "160px" }} {...params} />
                      )}
                      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>
          }
          columns={columns}
          data={data}
          progressPending={loading}
          pagination
          paginationServer
          paginationTotalRows={totalRows}
          onChangeRowsPerPage={handlePerRowsChange}
          onChangePage={handlePageChange}
        />
      </Grid>
    </>
  );
};
