import React, { useEffect, useState, useCallback } from "react";
import {
  Button,
  Checkbox,
  FormControlLabel,
  IconButton,
  TextField,
  Tooltip,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import VisibilityIcon from "@mui/icons-material/Visibility";
import { formatJustDate } from "../../../../utils/formatTime";
import { RiSearchLine } from "react-icons/ri";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterOrders = () => {
  const [selectedDate1, setSelectedDate1] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );
  const [selectedDate2, setSelectedDate2] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const [withDate, setWithDate] = useState(true);
  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 = useCallback(
    async (page) => {
      dispatch(LOADING_START());
      const response = await axios.get(
        `orders_for_kill_house/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }&page=${page}&page_size=${perPage}`
      );
      dispatch(LOADING_END());
      setData(response.data.results);
      setTotalRows(response.data.count);
    },
    [
      textValue,
      withDate,
      selectedDate1,
      selectedDate2,
      perPage,
      setData,
      setTotalRows,
      page,
      dispatch,
      selectedSubUser?.key,
    ]
  );

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

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.orderCode,
        formatJustDate(item?.date),
        item?.customerName,
        item?.customerMobile,
        item?.customerCity,
        item?.productType,
        item?.quantity?.toLocaleString(),
        item?.weight?.toLocaleString(),
        item?.status,
        item?.deliveryDate ? formatJustDate(item?.deliveryDate) : "-",
        <Tooltip title="مشاهده جزئیات" key={i}>
          <IconButton
            size={"small"}
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "جزئیات سفارش",
                  content: (
                    <Grid container gap={2}>
                      <Grid xs={12}>
                        <strong>کد سفارش:</strong> {item?.orderCode}
                      </Grid>
                      <Grid xs={12}>
                        <strong>مشتری:</strong> {item?.customerName}
                      </Grid>
                      <Grid xs={12}>
                        <strong>تلفن:</strong> {item?.customerMobile}
                      </Grid>
                      <Grid xs={12}>
                        <strong>شهر:</strong> {item?.customerCity}
                      </Grid>
                      <Grid xs={12}>
                        <strong>نوع محصول:</strong> {item?.productType}
                      </Grid>
                      <Grid xs={12}>
                        <strong>حجم:</strong> {item?.quantity?.toLocaleString()}{" "}
                        قطعه
                      </Grid>
                      <Grid xs={12}>
                        <strong>وزن:</strong> {item?.weight?.toLocaleString()}{" "}
                        کیلوگرم
                      </Grid>
                      <Grid xs={12}>
                        <strong>وضعیت:</strong> {item?.status}
                      </Grid>
                      <Grid xs={12}>
                        <strong>تاریخ ثبت:</strong> {formatJustDate(item?.date)}
                      </Grid>
                      {item?.deliveryDate && (
                        <Grid xs={12}>
                          <strong>تاریخ تحویل:</strong>{" "}
                          {formatJustDate(item?.deliveryDate)}
                        </Grid>
                      )}
                    </Grid>
                  ),
                })
              );
            }}
          >
            <VisibilityIcon fontSize="small" />
          </IconButton>
        </Tooltip>,
      ];
    });

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

  useEffect(() => {
    fetchApiData(1);
  }, [selectedSubUser?.key]);

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

    try {
      const response = await axios.get(
        `orders_for_kill_house/?role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&search=filter&value=${textValue}${
          withDate ? `&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
          container
          style={{
            borderStyle: "solid",
            borderWidth: "1px",
            padding: "10px",
            borderRadius: "15px",
            borderColor: "gray",
            justifyContent: "left",
          }}
        >
          <Grid>
            <FormControlLabel
              control={
                <Checkbox
                  checked={withDate}
                  onChange={() => setWithDate(!withDate)}
                  color="primary"
                />
              }
            />
          </Grid>

          <Grid>
            <DatePicker
              disabled={!withDate}
              label="از تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  style={{ width: "160px" }}
                  {...params}
                />
              )}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              disabled={!withDate}
              label="تا تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  style={{ width: "160px" }}
                  {...params}
                />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        </Grid>
        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              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>
  );
};
