import { Button, TextField, Typography, Tabs, Tab } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../components/grid/Grid";
import { AppContext } from "../../../contexts/AppContext";
import { SPACING } from "../../../data/spacing";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../lib/redux/slices/appSlice";
import { GuildReceiveBarOperation } from "../../guild/components/GuildReceiveBarOperation";
import { senfGetAllocationDashboardService } from "../../guild/services/senf-get-allocation-dashboard";
import { senfGetInventoryAllocatedService } from "../../guild/services/senf-get-inventory-allocated";
import { guildSalesInfoDashboardService } from "../../guild/services/guild-sales-info-dashboard";
import { getFaUserRole } from "../../../utils/getFaUserRole";
import { formatJustDate } from "../../../utils/formatTime";
import { checkPathStartsWith } from "../../../utils/checkPathStartsWith";
import ResponsiveTable from "../../../components/responsive-table/ResponsiveTable";
import { RiSearchLine } from "react-icons/ri";

export const SenfStock = () => {
  const dispatch = useDispatch();
  const [dataTable, setDataTable] = useState([]);
  const [statusTab, setStatusTab] = useState("pending");
  const [text, setText] = useState("");
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const {
    senfGetInventoryStock,
    senfGetInventoryAllocated,
    guildSalesInfoDashboard,
  } = useSelector((state) => state.generalSlice);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const handleRefreshServices = () => {
    dispatch(
      senfGetAllocationDashboardService({
        date1: selectedDate1,
        date2: selectedDate2,
        role_key: selectedSubUser?.key || "",
        search: text,
      })
    );
    dispatch(
      senfGetInventoryAllocatedService({
        date1: selectedDate1,
        date2: selectedDate2,
        role_key: selectedSubUser?.key || "",
        type: statusTab,
        search: text,
      })
    );
    dispatch(
      guildSalesInfoDashboardService({
        role_key: selectedSubUser?.key,
      })
    );
  };

  useEffect(() => {
    handleRefreshServices();
  }, [selectedDate1, selectedDate2, selectedSubUser?.key, statusTab]);

  useEffect(() => {
    const items = senfGetInventoryAllocated?.results || [];

    if (items.length > 0) {
      const d = items.map((item, i) => {
        let state = "";
        if (item?.receiverState === "accepted") {
          state = "تحویل گرفته شده";
        } else if (item?.receiverState === "rejected") {
          state = "رد شده";
        } else {
          state = "در انتظار تحویل";
        }

        const sellerRoleFa = getFaUserRole(item?.seller_type);
        const sellerName =
          item?.stewards?.user?.fullname ||
          item?.stewards?.name ||
          item?.killHouse?.name ||
          item?.toKillHouse?.name ||
          "-";
        const sellerMobile =
          item?.stewards?.user?.mobile ||
          item?.killHouse?.user?.mobile ||
          item?.toKillHouse?.user?.mobile ||
          "-";

        return [
          i + 1,
          `${sellerRoleFa} ${sellerName} (${sellerMobile})`,
          formatJustDate(item.date),
          (item?.weightOfCarcasses || 0).toLocaleString() + " کیلوگرم",
          item?.quota === "free" ? "آزاد" : "دولتی",
          <Grid container direction="column" key={item.key}>
            {/* <Typography variant="caption">
              {item?.receiverRealNumberOfCarcasses?.toLocaleString() + " قطعه"}
            </Typography> */}
            <Typography variant="caption">
              {item?.receiverRealWeightOfCarcasses?.toLocaleString() +
                " کیلوگرم"}
            </Typography>

            {/* {item?.receiverState === "pending" && (
              <Grid>
                <Button
                  onClick={() => {
                    dispatch(
                      OPEN_MODAL({
                        title: "ثبت/ویرایش تعداد و وزن تحویلی",
                        content: (
                          <RegisterEditDeliveryNumberAndWeight item={item} />
                        ),
                      })
                    );
                  }}
                >
                  {item?.receiverRealNumberOfCarcasses ? "ویرایش" : "ثبت"}
                </Button>
              </Grid>
            )} */}
          </Grid>,
          <Grid container direction="column" key={item.key} gap={SPACING.SMALL}>
            {item.receiverState === "pending" ? (
              <Button
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "ثبت تحویل بار",
                      content: (
                        <GuildReceiveBarOperation
                          item={item}
                          onSuccess={handleRefreshServices}
                        />
                      ),
                    })
                  );
                }}
              >
                تحویل بار
              </Button>
            ) : (
              state
            )}
          </Grid>,
        ];
      });

      setDataTable(d);
    } else {
      setDataTable([]);
    }
  }, [senfGetInventoryAllocated, dispatch]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());
    try {
      dispatch(
        senfGetAllocationDashboardService({
          date1: selectedDate1,
          date2: selectedDate2,
          role_key: checkPathStartsWith("senf") ? selectedSubUser?.key : "",
          search: text,
        })
      );
      dispatch(
        senfGetInventoryAllocatedService({
          date1: selectedDate1,
          date2: selectedDate2,
          role_key: checkPathStartsWith("senf") ? selectedSubUser?.key : "",
          type: statusTab,
          search: text,
        })
      );
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      dispatch(LOADING_END());
    }
  };

  return (
    <Grid container gap={SPACING.SMALL} pt={SPACING.MEDIUM}>
      <ResponsiveTable
        title="اطلاعات فروش"
        columns={[
          "وزن دولتی (کیلوگرم)",
          "وزن آزاد (کیلوگرم)",
          "فروش دولتی (کیلوگرم)",
          "فروش آزاد (کیلوگرم)",
          "وزن قطعه بندی (کیلوگرم)",
          "وزن انجماد (کیلوگرم)",
          "مانده دولتی (کیلوگرم)",
          "مانده آزاد (کیلوگرم)",
        ]}
        data={[
          [
            (
              guildSalesInfoDashboard?.totalGovernmentalInputWeight || 0
            ).toLocaleString(),
            (
              guildSalesInfoDashboard?.totalFreeInputWeight || 0
            ).toLocaleString(),
            (
              guildSalesInfoDashboard?.totalGovernmentalOutputWeight || 0
            ).toLocaleString(),
            (
              guildSalesInfoDashboard?.totalFreeOutputWeight || 0
            ).toLocaleString(),
            guildSalesInfoDashboard?.segmentationsWeight || "0",
            "0",
            (
              guildSalesInfoDashboard?.totalGovernmentalRemainWeight || 0
            ).toLocaleString(),
            (
              guildSalesInfoDashboard?.totalFreeRemainWeight || 0
            ).toLocaleString(),
          ],
        ]}
        noPagination
        isDashboard
      />
      <Grid
        container
        gap={SPACING.SMALL}
        alignItems="center"
        justifyContent="space-between"
        mb={2}
        mt={2}
      >
        <Grid container gap={SPACING.SMALL} alignItems="center">
          <DatePicker
            label="تاریخ شروع"
            id="date1"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
          <DatePicker
            label="تاریخ پایان"
            id="date2"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              value={text}
              onChange={(e) => setText(e.target.value)}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>
      <ResponsiveTable
        title="ورودی به انبار"
        columns={[
          "تعداد بار تخصیصی",
          "وزن لاشه در انتظار تحویل",
          "وزن لاشه تحویلی",
        ]}
        data={[
          [
            senfGetInventoryStock?.allocationsCount || 0,
            (
              (senfGetInventoryStock?.notEnteredWeight || 0) +
              (senfGetInventoryStock?.enteredWeight || 0)
            ).toLocaleString() + " کیلوگرم",
            (senfGetInventoryStock?.enteredWeight || 0).toLocaleString() +
              " کیلوگرم",
          ],
        ]}
        noPagination
        isDashboard
      />
      {/* Tabs for filtering by receiver state */}
      <Grid container justifyContent="center" xs={12} mt={SPACING.SMALL}>
        <Tabs
          value={statusTab}
          onChange={(_, value) => setStatusTab(value)}
          sx={{ borderBottom: 1, borderColor: "divider", mb: 1 }}
        >
          <Tab label="در انتظار تحویل" value="pending" />
          <Tab label="تحویل گرفته شده" value="accepted" />
        </Tabs>
      </Grid>

      <ResponsiveTable
        title={`بارهای اختصاصی ${
          statusTab === "pending" ? "در انتظار تحویل" : "تحویل گرفته شده"
        }`}
        columns={
          statusTab === "accepted"
            ? [
                "ردیف",
                "فروشنده",
                "تاریخ تخصیص",
                "وزن تخصیص",
                "نوع فروش",
                "وزن واقعی تحویلی",
              ]
            : [
                "ردیف",
                "فروشنده",
                "تاریخ تخصیص",
                "وزن تخصیص",
                "نوع فروش",
                "وزن واقعی تحویلی",
                "عملیات",
              ]
        }
        data={
          statusTab === "accepted"
            ? dataTable.map((row) => row.slice(0, -1))
            : dataTable
        }
      />
    </Grid>
  );
};
