import { useState, useEffect, useContext, useCallback } from "react";
import { Grid } from "../../../components/grid/Grid";
import { Button, TextField, Tooltip } from "@mui/material";
import axios from "axios";
import moment from "moment/moment";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { DatePicker } from "@mui/x-date-pickers";
import { useDispatch, useSelector } from "react-redux";
import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../utils/getRoleFromUrl";
import { SPACING } from "../../../data/spacing";
import ResponsiveTable from "../../../components/responsive-table/ResponsiveTable";
import { formatJustDate } from "../../../utils/formatTime";
import { SupporterSettlementOperation } from "./supporter-settlement-operation/SupporterSettlementOperation";
import SlaughterBuyPdfKillRequest from "../../province/components/province-settlement-pdf-kill-request/ProvinceSettlementPdfKillRequest";

const SupporterSettlement = () => {
  const dispatch = useDispatch();

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [tableData, setTableData] = useState([]);
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);

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

  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const fetchApiData = useCallback(async () => {
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `direct-buying-requests/?role=${getRoleFromUrl()}&status=active"&search=filter&value=${
          textValue || ""
        }&date1=${selectedDate1}&date2=${selectedDate2}&page=1&page_size=${perPage}`
      );
      dispatch(LOADING_END());
      setData(response?.data?.results);
      setTotalRows(response?.data?.count);
    } catch (error) {
      dispatch(LOADING_END());
    }
  }, [selectedDate1, selectedDate2, perPage, page, textValue, dispatch]);

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

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

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

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

    try {
      const response = await axios.get(
        `direct-buying-requests/?role=${getRoleFromUrl()}&status=${"active"}&date1=${selectedDate1}&date2=${selectedDate2}&search=filter&value=${
          textValue || ""
        }`
      );
      setData(response?.data?.results);
      setTotalRows(response?.data?.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

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

  const updateTable = useCallback(() => {
    fetchApiData(1);
  }, [fetchApiData]);

  useEffect(() => {
    const d = data?.map((item, i) => {
      let paymentStatusText;
      switch (item?.paymentDeadlineState) {
        case "pending":
          paymentStatusText = "بارگزاری سند مالی";
          break;
        case "checking":
          paymentStatusText = "بررسی مالی اتحادیه";
          break;
        case "accepted":
          paymentStatusText = "تایید شده";
          break;

        case "rejected":
          paymentStatusText = "برگشت داده شده";
          break;
        case "archive":
          paymentStatusText = "بایگانی شده";
          break;
        default:
          paymentStatusText = "وضعیت نامشخص";
      }
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,

        formatJustDate(item?.killRequest?.createDate),

        formatJustDate(item?.killRequest?.reciveDate),
        `${item?.killRequest?.killHouse?.name} (${item?.killRequest?.killHouse?.mobile})`,
        `${item?.killRequest?.poultry?.age}`,
        item?.killRequest?.freeDirectBuying ? "آزاد" : "دولتی",
        item?.killRequest?.killHouse
          ? item?.killRequest?.killHouse?.name
          : item?.killRequest?.slaughterHouse,

        `${item?.killRequest?.poultry?.fullname} (${item?.killRequest?.poultry.mobile})`,

        item?.generalInfo?.age,

        `${
          item?.killRequest?.chickenBreed
            ? item?.killRequest?.chickenBreed
            : "-"
        }`,
        item?.totalKilledQuantity?.toLocaleString(),
        item?.generalInfo?.IndexWeight,

        item?.totalKilledWeight?.toLocaleString(),

        item?.killRequest?.amount?.toLocaleString(),

        item?.generalInfo?.totalAmount?.toLocaleString(),

        formatJustDate(item?.paymentDeadlineDate),
        item?.extensionPaymentDeadlineDate
          ? formatJustDate(item?.extensionPaymentDeadlineDate)
          : "-",
        <SlaughterBuyPdfKillRequest key={i} pdf_key={item?.killRequest?.key} />,
        item?.generalInfo?.totalPaidAmount.toLocaleString(),

        paymentStatusText,
        item?.paymentDeadlineCheckerFullname,
        formatJustDate(item?.paymentDeadlineCheckDate),
        item?.paymentDeadlineArchiveMessage,

        <SupporterSettlementOperation
          updateTable_data={updateTable}
          key={`ops-${i}`}
          item={item}
          item_key={item?.key}
        />,
      ];
    });

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

  return (
    <>
      <Grid
        container
        lg={12}
        xs={12}
        justifyContent="start"
        alignItems="center"
      >
        <Grid
          container
          alignItems="center"
          mb={SPACING.SMALL}
          gap={SPACING.SMALL}
        >
          <form onSubmit={handleSubmit}>
            <Grid container alignItems="center" gap={SPACING.SMALL}>
              <TextField
                size="small"
                autoComplete="off"
                label="جستجو"
                variant="outlined"
                style={{ width: 250 }}
                onChange={handleTextChange}
              />
              <Button
                // disabled={!textValue}
                type="submit"
                onClick={handleSubmit}
                endIcon={<RiSearchLine />}
              >
                جستجو
              </Button>
              <Grid container gap={2}>
                <DatePicker
                  label="از تاریخ"
                  id="date"
                  renderInput={(params) => (
                    <TextField style={{ width: "160px" }} {...params} />
                  )}
                  value={selectedDate1}
                  onChange={(e) => {
                    setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                  }}
                />
                <DatePicker
                  label="تا تاریخ"
                  id="date"
                  renderInput={(params) => (
                    <TextField style={{ width: "160px" }} {...params} />
                  )}
                  value={selectedDate2}
                  onChange={(e) => {
                    setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                  }}
                />
              </Grid>

              <Grid>
                <Tooltip title="خروجی اکسل">
                  <a
                    href={`${
                      axios.defaults.baseURL
                    }direct_purchase_excel/?date1=${selectedDate1}&date2=${selectedDate2}&role=${getRoleFromUrl()}&key=${userKey}`}
                    rel="noreferrer"
                  >
                    <Button color="success">
                      <RiFileExcel2Fill size={32} />
                    </Button>
                  </a>
                </Tooltip>
              </Grid>
            </Grid>
          </form>
        </Grid>

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

export default SupporterSettlement;
