import React, { useContext, useEffect, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import moment from "moment";
import axios from "axios";
import {
  DRAWER,
  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 { SPACING } from "../../../../data/spacing";
import { useDispatch, useSelector } from "react-redux";
import { Button, Tab, Tabs, TextField, Tooltip } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { slaughterGetExportAllowState } from "../../services/slaughter-get-export-allow-state";
import { SlaughterSubmitExport } from "../slaughter-submit-export/SlaughterSubmitExport";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { SlaughterExportOptions } from "../slaughter-export-options/SlaughterExportOptions";
import { EnterAuthCodeDirectBuy } from "../enter-auth-code-direct-buy/EnterAuthCodeDirectBuy";
import { RiFileExcel2Fill } from "react-icons/ri";
import { RiSearchLine } from "react-icons/ri";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterExport = () => {
  const dispatch = useDispatch();
  const [exportData, setExportData] = useState();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  useEffect(() => {
    dispatch(
      slaughterGetExportAllowState({
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    ).then((r) => {
      setExportData(r.payload.data);
    });
  }, [selectedSubUser?.key]);

  const [activeTab, setActiveTab] = useState(0);

  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

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

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

  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 [tableDataArchive, setTableDataArchive] = useState([]);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `kill_request/?export=true&type=${
        activeTab === 0 ? "pending" : "archive"
      }&search=filter&value=${textValue}&role=${getRoleFromUrl()}${
        checkPathStartsWith("slaughter")
          ? `&role_key=${selectedSubUser?.key}`
          : ""
      }&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

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

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

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

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

  const getItemState = (item) => {
    let state = "";
    if (item.exportState === "pending") {
      state = "در انتظار تایید";
    } else if (item.exportState === "rejected") {
      state = "رد شده";
    } else if (item.exportState === "accepted") {
      state = "تایید شده";
    } else if (item.exportState === "deleted") {
      state = "حذف شده";
    }
    return state;
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        formatJustDate(item?.createDate),
        formatJustDate(item.reciveDate),
        `${item.killHouse.name} (${item.killHouse.killHouseOperator.user.mobile})`,
        item?.slaughterHouse
          ? item?.slaughterHouse?.name
          : item?.killHouse?.name,
        item?.exportCountry,
        `${item?.poultry?.userprofile?.fullName} (${item?.poultry?.userprofile?.mobile})`,
        item.killCapacity,
        item.IndexWeight,
        (item.IndexWeight * item.killCapacity)?.toLocaleString(),
        <>
          {item?.inputDirectBuyingCode ? (
            item?.inputDirectBuyingCode
          ) : (
            <Button
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    title: "ثبت کد احراز",
                    content: (
                      <EnterAuthCodeDirectBuy
                        item={item}
                        updateTable={updateTable}
                      />
                    ),
                  })
                );
              }}
            >
              ثبت کداحراز
            </Button>
          )}
        </>,
        getItemState(item),

        activeTab === 0 ? (
          <SlaughterExportOptions
            key={i}
            updateTable={updateTable}
            item={item}
          />
        ) : (
          "-"
        ),
      ];
    });

    setTableData(d);

    const a = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        formatJustDate(item?.createDate),
        formatJustDate(item.reciveDate),
        `${item.killHouse.name} (${item.killHouse.killHouseOperator.user.mobile})`,
        item?.slaughterHouse
          ? item?.slaughterHouse?.name
          : item?.killHouse?.name,
        item?.exportCountry,
        `${item?.poultry?.userprofile?.fullName} (${item?.poultry?.userprofile?.mobile})`,
        item.killCapacity,
        item.IndexWeight,
        (item.IndexWeight * item.killCapacity)?.toLocaleString(),
        getItemState(item),
        item?.acceptRejectDate ? formatTime(item?.acceptRejectDate) : "-",
        item?.directBuyingMessage,
      ];
    });

    setTableDataArchive(a);
  }, [data]);

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

    try {
      const response = await axios.get(
        `kill_request/?export=true&type=${
          activeTab === 0 ? "pending" : "archive"
        }&role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&search=filter&value=${textValue}&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);
    }
  };
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  return (
    <Grid container direction="column" flexWrap="nowrap" mt={SPACING.SMALL}>
      <Grid
        container
        justifyContent="center"
        alignItems="center"
        my={SPACING.SMALL}
      >
        <Tabs
          scrollButtons="auto"
          variant="scrollable"
          allowScrollButtonsMobile
          value={activeTab}
          onChange={handleTabChange}
        >
          <Tab label="درخواست های جدید" />
          <Tab label="بایگانی" />
        </Tabs>
      </Grid>
      <Grid
        container
        mt={SPACING.MEDIUM}
        alignItems="center"
        justifyContent="center"
        gap={2}
      >
        <Button
          variant="contained"
          disabled={!exportData?.exportStatus}
          onClick={() => {
            dispatch(
              DRAWER({
                title: "ثبت درخواست صادرات",
                content: <SlaughterSubmitExport updateTable={updateTable} />,
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
              })
            );
          }}
        >
          ثبت درخواست صادرات
        </Button>
        <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>
              <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>
            {activeTab === 1 && (
              <Grid>
                <Tooltip title="خروجی اکسل">
                  <a
                    href={`${
                      axios.defaults.baseURL
                    }export_kill_house_excel/?date1=${selectedDate1}&date2=${selectedDate2}&role=${getRoleFromUrl()}${
                      checkPathStartsWith("slaughter")
                        ? `&role_key=${selectedSubUser?.key}`
                        : ""
                    }&key=${userKey}`}
                    rel="noreferrer"
                  >
                    <Button color="success">
                      <RiFileExcel2Fill size={32} />
                    </Button>
                  </a>
                </Tooltip>
              </Grid>
            )}
          </Grid>
        </form>

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