import {
  Button,
  Checkbox,
  Divider,
  FormControlLabel,
  Pagination,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import axios from "axios";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { PageTable } from "../../../../components/page-table/PageTable";
import { SPACING } from "../../../../data/spacing";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { formatJustDate } from "../../../../utils/formatTime";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { SlaughterPayingFeesOverview } from "../slaughter-paying-fees-overview/SlaughterPayingFeesOverview";
import { SlaughterUnpaidFeesDetails } from "../slaughter-unpaid-fees-details/SlaughterUnpaidFeesDetails";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import BoxList from "../../../../components/box-list/BoxList";
import { AppContext } from "../../../../contexts/AppContext";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";

export const SlaughterUnpaidFees = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [withDate, setWithDate] = useState(false);
  const [checked, setChecked] = useState(false);

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

  const dispatch = useDispatch();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(50);
  const userInfo = useSelector((state) => state.userSlice);
  const [selectedItems, setSelectedItems] = useState([]);
  const [selectedItemsFull, setSelectedItemsFull] = useState([]);
  const [dataTableM, setDataTableM] = useState([]);
  const [totalSelectedFees, setTotalSelectedFees] = useState(0);

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

  const totalSelectedWeight = selectedItemsFull?.reduce((accumulator, item) => {
    if (selectedItems.includes(item.provinceRequest.provinceKillRequestKey)) {
      return (
        accumulator + item?.provinceRequest?.provinceKillRequestTotalWeight
      );
    }
    return accumulator;
  }, 0);

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

  const handleSelectedItems = (itemKey, itemFull) => {
    setSelectedItems((prevSelectedItems) => {
      if (prevSelectedItems.includes(itemKey)) {
        const filtered = prevSelectedItems.filter((item) => item !== itemKey);
        setSelectedItemsFull((prevSelectedItemsFull) =>
          prevSelectedItemsFull.filter(
            (item) => item.provinceRequest.provinceKillRequestKey !== itemKey
          )
        );
        return filtered;
      } else {
        setSelectedItemsFull((prevSelectedItemsFull) => [
          ...prevSelectedItemsFull,
          itemFull,
        ]);
        return [...prevSelectedItems, itemKey];
      }
    });
  };

  useEffect(() => {
    const updateTotalSelectedFees = async () => {
      await setTotalSelectedFees((prevTotalSelectedFees) => {
        let accumulatedFees = prevTotalSelectedFees;

        data.forEach((item) => {
          if (checked) {
            if (
              accumulatedFees + item.provinceRequest.totalAmount <=
              1000000000
            ) {
              accumulatedFees += item.provinceRequest.totalAmount;
              handleSelectedItems(
                item.provinceRequest.provinceKillRequestKey,
                item
              );
            }
          } else {
            setSelectedItems([]);
            setSelectedItemsFull([]);
          }
        });
        return accumulatedFees;
      });
    };

    updateTotalSelectedFees();
  }, [checked]);

  useEffect(() => {
    const newTotalSelectedFees = selectedItemsFull?.reduce(
      (accumulator, item) => {
        if (
          selectedItems.includes(item.provinceRequest.provinceKillRequestKey)
        ) {
          return accumulator + item?.provinceRequest?.totalAmount;
        }
        return accumulator;
      },
      0
    );

    setTotalSelectedFees(newTotalSelectedFees);
  }, [selectedItemsFull, selectedItems]);

  const fetchApiData = async (page, textValue) => {
    setLoading(true);
    const response = await axios.get(
      `province_wage/?type=unpaid&search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }`
    );
    setData(response.data.results);
    setTotalRows(response.data.count);
    setLoading(false);
    dispatch(LOADING_END());
  };

  const [page, setPage] = useState(0);
  const handleChangePageM = (event, newPage) => {
    dispatch(LOADING_START());
    setPage(newPage);
    fetchApiData(newPage + 1, textValue);
  };

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

  const handlePerRowsChange = async (newPerPage, page) => {
    setLoading(true);
    const response = await axios.get(
      `province_wage/?type=unpaid&search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${newPerPage}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }`
    );
    setData(response.data.results);
    setTotalRows(response.data.count);
    setPerPage(newPerPage);

    setLoading(false);
  };

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

  const updateTable = () => {
    return fetchApiData(1);
  };

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

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

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

  const columns = [
    {
      name: "انتخاب",
      selector: (item) => (
        <FormControlLabel
          control={
            <Checkbox
              checked={selectedItems.includes(
                item.provinceRequest.provinceKillRequestKey
              )}
              onChange={() =>
                handleSelectedItems(
                  item.provinceRequest.provinceKillRequestKey,
                  item
                )
              }
              color="primary"
            />
          }
        />
      ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "50px",
    },
    {
      name: "کدسفارش",
      selector: (item) => item?.provinceRequest?.orderCode,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "مرغدار (تلفن)",
      selector: (item) =>
        `${item?.provinceRequest?.poultryFullname} (${item?.provinceRequest?.poultryMobile})`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "شهر",
      selector: (item) => `${item?.provinceRequest?.poultryCity}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "تاریخ کشتار",
      selector: (item) => formatJustDate(item?.provinceRequest?.sendDate),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "محل کشتار",
      selector: (item) => item?.provinceRequest?.killPlace,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    // {
    //   name: "نژاد",
    //   selector: (item) => item?.provinceRequest?.breed,
    //   sortable: true,
    //   wrap: true,
    //   allowOverflow: true,
    //   center: true,
    //   // width: "80px",
    // },
    {
      name: "تعداد (قطعه)",
      selector: (item) =>
        item?.provinceRequest?.provinceKillRequestQuantity?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "وزن (کیلوگرم)",
      selector: (item) =>
        item?.provinceRequest?.provinceKillRequestTotalWeight?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "میانگین وزنی (کیلوگرم)",
      selector: (item) => item?.provinceRequest?.indexWeight,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "تعرفه اتحادیه (ریال)",
      selector: (item) => item?.provinceRequest?.wage?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "مبلغ کل تعرفه (ریال)",
      selector: (item) => item?.provinceRequest?.totalAmount?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "جزییات سفارش",
      selector: (item) => (
        <Button
          onClick={() => {
            dispatch(
              DRAWER({
                top: true,
                title: "جزییات سفارش",
                content: <SlaughterUnpaidFeesDetails item={item} />,
              })
            );
          }}
        >
          مشاهده
        </Button>
      ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
  ];

  const paymentDisabled =
    !selectedItems.length || totalSelectedFees > 1000000000;

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={1}
      paddingTop={2}
      mb={1}
      width="100%"
    >
      <Grid container alignItems="center" gap={SPACING.SMALL}>
        <Typography variant="body2">انتخاب همه</Typography>
        <Checkbox
          checked={checked}
          onChange={() => {
            setChecked(!checked);
          }}
          color="primary"
        />

        <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>
        <form onSubmit={handleSubmit}>
          <TextField
            id="outlined-basic"
            size="small"
            autoComplete="off"
            label="جستجو"
            variant="outlined"
            style={{ width: 200 }}
            onChange={handleTextChange}
          />
          <Button
            // disabled={!textValue}
            type="submit"
            onClick={handleSubmit}
            endIcon={<RiSearchLine />}
          >
            جستجو
          </Button>
        </form>

        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }slaughterhouse_fee_not_paid_excel/?key=${
              userInfo?.userProfile?.key
            }${
              withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
            }`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>
      <Grid container>
        <Grid xs={12}>
          <Typography
            variant="body2"
            color={paymentDisabled ? "error" : "primary"}
          >
            مبلغ کل: {totalSelectedFees.toLocaleString()} ریال
          </Typography>
          <Divider width="100%" />
          <Typography variant="body2" color={"gray"}>
            تعداد سفارش: {selectedItems?.length}
          </Typography>
        </Grid>
      </Grid>

      <Button
        variant="contained"
        disabled={paymentDisabled}
        onClick={() => {
          dispatch(
            OPEN_MODAL({
              title: "پرداخت تعرفه ",
              content: (
                <SlaughterPayingFeesOverview
                  updateTable={updateTable}
                  selectedItems={selectedItems}
                  totalSelectedFees={totalSelectedFees}
                  totalSelectedWeight={totalSelectedWeight}
                />
              ),
            })
          );
        }}
      >
        پرداخت تعرفه
      </Button>
    </Grid>
  );

  const isMobile = window.innerWidth <= 600;

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        <FormControlLabel
          key={i}
          control={
            <Checkbox
              checked={selectedItems.includes(
                item.provinceRequest.provinceKillRequestKey
              )}
              onChange={() =>
                handleSelectedItems(
                  item.provinceRequest.provinceKillRequestKey,
                  item
                )
              }
              color="primary" // Change the color to your preference
            />
          }
        />,
        item?.provinceRequest?.orderCode,
        `${item?.provinceRequest?.poultryCity}`,
        item?.provinceRequest?.totalAmount?.toLocaleString(),
        <Button
          key={i}
          onClick={() => {
            dispatch(
              DRAWER({
                top: true,
                title: "جزییات سفارش",
                content: <SlaughterUnpaidFeesDetails item={item} />,
              })
            );
          }}
        >
          مشاهده
        </Button>,
      ];
    });

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

  return (
    <Grid container justifyContent="center" gap={SPACING.SMALL}>
      <Grid xs={12}>
        <Typography color="error">تعرفه های پرداخت نشده</Typography>
      </Grid>
      <Divider width="100%" />
      {isMobile ? (
        <>
          {tableTitle}
          <BoxList
            columns={[
              "انتخاب",
              "کد سفارش",
              "شهر",
              "مبلغ کل تعرفه (ریال)",
              "جزئیات سفارش",
            ]}
            data={dataTableM}
          />
          <Pagination
            count={Math.ceil(totalRows / 10)}
            page={page + 1}
            variant="outlined"
            onChange={(event, newPage) => {
              handleChangePageM(event, newPage - 1);
            }}
          />
        </>
      ) : (
        <PageTable
          title={tableTitle}
          columns={columns}
          data={data}
          progressPending={loading}
          pagination
          paginationServer
          paginationTotalRows={totalRows}
          onChangeRowsPerPage={handlePerRowsChange}
          onChangePage={handlePageChange}
        />
      )}
    </Grid>
  );
};
