import React, { useContext, useEffect, useState } from "react";
import moment from "moment";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import {
  Button,
  Chip,
  IconButton,
  Tab,
  Tabs,
  TextField,
  Tooltip,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { AppContext } from "../../../../contexts/AppContext";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { SlaughterFreeBuyOperations } from "../../../slaughter-house/components/slaughter-free-buy-operations/SlaughterFreeBuyOperations";
import { EnterAuthCodeDirectBuy } from "../../../slaughter-house/components/enter-auth-code-direct-buy/EnterAuthCodeDirectBuy";
import { RiFileExcel2Fill } from "react-icons/ri";
import { RiSearchLine } from "react-icons/ri";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";

export const ProvinceExport = () => {
  const dispatch = useDispatch();

  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()}&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);
  }, []);

  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
          ) : (
            <Tooltip title="ثبت کد احراز" placement="top">
              <IconButton
                color="primary"
                size="small"
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "ثبت کد احراز",
                      size: "auto",
                      content: (
                        <EnterAuthCodeDirectBuy
                          item={item}
                          updateTable={updateTable}
                        />
                      ),
                    })
                  );
                }}
              >
                <AddCircleOutlineIcon fontSize="small" />
              </IconButton>
            </Tooltip>
          )}
        </>,
        <Chip
          key={`${item.key}-state`}
          label={getItemState(item)}
          color={
            getItemState(item) === "تایید شده"
              ? "success"
              : getItemState(item) === "رد شده"
              ? "error"
              : getItemState(item) === "حذف شده"
              ? "default"
              : "warning"
          }
          size="small"
          variant="outlined"
        />,
        <SlaughterFreeBuyOperations
          key={item}
          item={item}
          updateTable={updateTable}
        />,
      ];
    });

    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]);

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

  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()}&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}
      >
        <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()}&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>
  );
};
