import { useState, useEffect, useContext } from "react";
import {
  Button,
  TextField,
  Tooltip,
  Tab,
  Tabs,
  Box,
  Checkbox,
} from "@mui/material";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import { Grid } from "../../../../components/grid/Grid";
import moment from "moment/moment";

import axios from "axios";
import { useDispatch, useSelector } from "react-redux";

import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { DatePicker } from "@mui/x-date-pickers";
import { ProvinceSettlementOperation } from "../../components/province-settlement-operation/provinceSettlementOperation";

import { SPACING } from "../../../../data/spacing";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { formatJustDate } from "../../../../utils/formatTime";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { AppContext } from "../../../../contexts/AppContext";
import ProvinceSettlementPdfKillRequest from "../province-settlement-pdf-kill-request/ProvinceSettlementPdfKillRequest";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const ProvinceSettlement = () => {
  const dispatch = useDispatch();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const [tableData, setTableData] = useState([]);
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [withDate, setWithDate] = useState(false);
  const [page, setPage] = useState(1);
  const [value, setValue] = useState("0");
  const [textValue, setTextValue] = useState("");
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `direct-buying-requests/?role=${getRoleFromUrl()}${
        checkPathStartsWith("province")
          ? `&role_key=${selectedSubUser?.key}`
          : ""
      }&status=${value === "0" ? "active" : "archive"}&search=filter&value=${
        textValue || ""
      }${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }&page=${page}&page_size=${perPage}`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  useEffect(() => {
    fetchApiData(1);
  }, [
    dispatch,
    selectedDate1,
    selectedDate2,
    perPage,
    value,
    withDate,
    selectedSubUser?.key,
  ]);

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  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?.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)
          : "-",
        <ProvinceSettlementPdfKillRequest
          key={i}
          pdf_key={item?.killRequest?.key}
        />,
        item?.generalInfo?.totalPaidAmount.toLocaleString(),

        paymentStatusText,
        item?.paymentDeadlineCheckerFullname,
        formatJustDate(item?.paymentDeadlineCheckDate),
        item?.paymentDeadlineArchiveMessage,
        ...(value === "0"
          ? [
              <ProvinceSettlementOperation
                updateTable_data={updateTable}
                key={`ops-${i}`}
                item={item}
                item_key={item?.key}
              />,
            ]
          : []),
      ];
    });

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

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

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

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  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()}${
          checkPathStartsWith("province")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&status=${value === "0" ? "active" : "archive"}${
          withDate ? `&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);
    }
  };

  return (
    <>
      <Grid
        container
        alignItems="center"
        mb={SPACING.SMALL}
        gap={SPACING.SMALL}
        mt={SPACING.MEDIUM}
      >
        <form onSubmit={handleSubmit}>
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <Grid
              container
              gap={1}
              style={{
                borderStyle: "solid",
                borderWidth: "1px",
                padding: "5px",
                borderRadius: "15px",
                borderColor: "gray",
                justifyContent: "left",
              }}
              alignItems="center"
            >
              <Checkbox
                icon={<ToggleOffOutlinedIcon />}
                checkedIcon={<ToggleOnIcon />}
                checked={withDate}
                onChange={() => setWithDate(!withDate)}
                color="primary"
                size="large"
              />
              <Grid>
                <DatePicker
                  disabled={!withDate}
                  label="از تاریخ"
                  id="date"
                  renderInput={(params) => (
                    <TextField
                      size="small"
                      sx={{ width: { xs: "126px", md: "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"
                      sx={{ width: { xs: "126px", md: "160px" } }}
                      {...params}
                    />
                  )}
                  value={selectedDate2}
                  onChange={(e) => {
                    setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                  }}
                />
              </Grid>
            </Grid>
            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
            <Grid>
              <Tooltip title="خروجی اکسل">
                <a
                  href={`${
                    axios.defaults.baseURL
                  }direct_purchase_excel/?date1=${selectedDate1}&date2=${selectedDate2}&role=${getRoleFromUrl()}${
                    checkPathStartsWith("province")
                      ? `&role_key=${selectedSubUser?.key}`
                      : ""
                  }&key=${userKey}`}
                  rel="noreferrer"
                >
                  <Button color="success">
                    <RiFileExcel2Fill size={32} />
                  </Button>
                </a>
              </Tooltip>
            </Grid>
          </Grid>
        </form>
      </Grid>
      <Box sx={{ display: "flex", justifyContent: "center" }}>
        <Tabs
          value={value}
          onChange={handleChange}
          sx={{
            justifyContent: "center",
          }}
        >
          <Tab value="0" label="فعال" />
          <Tab value="1" label="بایگانی" />
        </Tabs>
      </Box>

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

export default ProvinceSettlement;
