import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  TextField,
  Switch,
  FormControlLabel,
  IconButton,
  Button,
  Typography,
} from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import SearchIcon from "@mui/icons-material/Search";
import { SPACING } from "../../../../data/spacing";
import { AppContext } from "../../../../contexts/AppContext";
import {
  provinceGetWarehouseArchive,
  provinceDeleteWarehouseArchive,
} from "../../services/province-warehouse-archive";
import { provinceGetTotalKillhouseArchiveDashboard } from "../../services/province-get-total-killhouse-remain-weight";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { numberDigitSeperator } from "../../../../utils/numberDigitSeperator";
import { useLocation } from "react-router-dom";
import { OPEN_MODAL, CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const ProvinceDispensersStockSlugArchive = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const location = useLocation();
  const pathSegments = location.pathname.split("/").filter(Boolean);
  const isStewardPage = pathSegments.includes("steward");
  const nameColumnLabel = isStewardPage ? "نام مباشر" : "نام کشتارگاه";
  const [tableData, setTableData] = useState([]);
  const [tablePage, setTablePage] = useState(1);
  const [tablePageSize, setTablePageSize] = useState(10);
  const [tableTotalRows, setTableTotalRows] = useState(0);
  const [dashboardTableData, setDashboardTableData] = useState([]);
  const [dashboardPage, setDashboardPage] = useState(1);
  const [dashboardPageSize, setDashboardPageSize] = useState(10);
  const [dashboardTotalRows, setDashboardTotalRows] = useState(0);
  const [dashboardSearchValue, setDashboardSearchValue] = useState("");
  const [dateRangeEnabled, setDateRangeEnabled] = useState(false);
  const [selectedDate1, setSelectedDate1] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );
  const [selectedDate2, setSelectedDate2] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );

  const handleDeleteWarehouseItem = (key) => {
    dispatch(
      OPEN_MODAL({
        title: "تأیید حذف",
        size: "auto",
        content: (
          <Grid container spacing={2}>
            <Grid
              item
              xs={12}
              container
              justifyContent="center"
              alignItems="center"
            >
              <Typography variant="body1">
                آیا از حذف این بایگانی اطمینان دارید؟
              </Typography>
            </Grid>
            <Grid item xs={6} mt={4}>
              <Button
                fullWidth
                variant="contained"
                color="error"
                onClick={() => {
                  dispatch(CLOSE_MODAL());
                  dispatch(
                    provinceDeleteWarehouseArchive({
                      key,
                      ownerType: isStewardPage ? "steward" : "kill_house",
                    })
                  ).then((r) => {
                    if (r.payload?.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error",
                      });
                    } else {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "حذف با موفقیت انجام شد",
                        severity: "success",
                      });
                      fetchWarehouseData();
                    }
                  });
                }}
              >
                بله
              </Button>
            </Grid>
            <Grid item xs={6} mt={4}>
              <Button
                fullWidth
                variant="outlined"
                onClick={() => dispatch(CLOSE_MODAL())}
              >
                خیر
              </Button>
            </Grid>
          </Grid>
        ),
      })
    );
  };

  const fetchDashboardData = () => {
    const params = {
      search: "filter",
      value: dashboardSearchValue,
      page: dashboardPage,
      page_size: dashboardPageSize,
      ...(isStewardPage ? { owner_type: "steward" } : { role: "SuperAdmin" }),
    };

    if (dateRangeEnabled) {
      params.date1 = selectedDate1;
      params.date2 = selectedDate2;
    }

    dispatch(provinceGetTotalKillhouseArchiveDashboard(params)).then((r) => {
      if (r.payload?.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else if (r.payload?.data) {
        const apiData = r.payload.data.results || [];
        setDashboardTotalRows(r.payload.data.count || 0);

        const data = apiData.map((item, index) => {
          const info = item?.info || {};
          const normalizeInfoValue = (...keys) => {
            for (const key of keys) {
              if (info?.[key] !== undefined && info?.[key] !== null) {
                return info[key];
              }
            }
            return 0;
          };

          const nameValue = isStewardPage
            ? item?.guilds_name || item?.guildsName || item?.name || "نامشخص"
            : item?.name || "نامشخص";

          return [
            (dashboardPage - 1) * dashboardPageSize + index + 1,
            nameValue,
            numberDigitSeperator(
              normalizeInfoValue("total_count", "totalCount")
            ) || 0,
            numberDigitSeperator(
              normalizeInfoValue(
                "total_governmental_count",
                "totalGovernmentalCount"
              )
            ) || 0,
            numberDigitSeperator(
              normalizeInfoValue("total_free_count", "totalFreeCount")
            ) || 0,
            numberDigitSeperator(
              normalizeInfoValue("total_weight", "totalWeight")
            ) || 0,
            numberDigitSeperator(
              normalizeInfoValue(
                "total_governmental_weight",
                "totalGovernmentalWeight"
              )
            ) || 0,
            numberDigitSeperator(
              normalizeInfoValue("total_free_weight", "totalFreeWeight")
            ) || 0,
          ];
        });

        setDashboardTableData(data);
      }
    });
  };

  const fetchWarehouseData = () => {
    const params = {
      search: "filter",
      value: "",
      page: tablePage,
      page_size: tablePageSize,
      ...(isStewardPage
        ? { archive_type: "steward", owner_type: "steward" }
        : {}),
    };

    if (dateRangeEnabled) {
      params.date1 = selectedDate1;
      params.date2 = selectedDate2;
    }

    dispatch(provinceGetWarehouseArchive(params)).then((r) => {
      if (r.payload?.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else if (r.payload?.data) {
        const apiData = r.payload.data.results || [];
        const totalCount = r.payload.data.count || 0;
        setTableTotalRows(totalCount);

        if (apiData.length === 0 && totalCount > 0 && tablePage > 1) {
          setTablePage((prev) => Math.max(prev - 1, 1));
          return;
        }

        const data = apiData.map((item, index) => {
          const killHouse = item?.killHouse || {};
          const steward = item?.steward || {};
          const guild = item?.guild || {};

          const createDateValue = item?.createDate;
          const registererMobile = item?.registererMobile || "-";
          const registererName = item?.registerer || "-";
          const quotaLabel = item?.quota === "free" ? "آزاد" : "دولتی";
          const description = item?.description || "-";
          const archiveKey = item?.key;

          const nameValue = isStewardPage
            ? item?.guildsName ||
              steward?.guildsName ||
              steward?.fullname ||
              guild?.name ||
              item?.ownerName ||
              killHouse?.name ||
              "نامشخص"
            : killHouse?.name || item?.ownerName || "نامشخص";

          const cityValue = isStewardPage
            ? item?.guildsCity ||
              steward?.city ||
              guild?.city ||
              item?.ownerCity ||
              killHouse?.city ||
              "-"
            : killHouse?.city || item?.ownerCity || "-";

          return [
            (tablePage - 1) * tablePageSize + index + 1,
            createDateValue ? formatTime(createDateValue) : "-",
            item?.date ? formatJustDate(item.date) : "-",
            nameValue,
            cityValue,
            numberDigitSeperator(item?.weight || 0) || 0,
            quotaLabel,
            registererName,
            registererMobile,
            description,
            <IconButton
              key={`delete-${archiveKey}`}
              color="error"
              onClick={() => handleDeleteWarehouseItem(archiveKey)}
              size="small"
            >
              <DeleteIcon />
            </IconButton>,
          ];
        });

        setTableData(data);
      }
    });
  };

  useEffect(() => {
    setTablePage(1);
  }, [selectedDate1, selectedDate2, dateRangeEnabled]);

  useEffect(() => {
    fetchWarehouseData();
  }, [
    selectedDate1,
    selectedDate2,
    dateRangeEnabled,
    tablePage,
    tablePageSize,
  ]);

  useEffect(() => {
    fetchDashboardData();
  }, [
    selectedDate1,
    selectedDate2,
    dateRangeEnabled,
    dashboardPage,
    dashboardPageSize,
  ]);

  return (
    <Grid
      container
      direction="column"
      alignItems="center"
      spacing={2}
      px={2}
      mt={SPACING.SMALL}
    >
      <Grid>
        <Grid container alignItems="center" gap={SPACING.SMALL} pt={1}>
          <FormControlLabel
            control={
              <Switch
                checked={dateRangeEnabled}
                onChange={(e) => setDateRangeEnabled(e.target.checked)}
                color="primary"
              />
            }
          />

          <Grid>
            <DatePicker
              label="از تاریخ"
              id="date1"
              renderInput={(params) => (
                <TextField style={{ width: "160px" }} {...params} />
              )}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              label="تا تاریخ"
              id="date2"
              renderInput={(params) => (
                <TextField style={{ width: "160px" }} {...params} />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid container alignItems="center" gap={SPACING.TINY}>
            <TextField
              label={`جستجو در ${isStewardPage ? "مباشرها" : "کشتارگاه‌ها"}`}
              variant="outlined"
              size="small"
              sx={{ width: "240px" }}
              value={dashboardSearchValue}
              onChange={(e) => setDashboardSearchValue(e.target.value)}
              onKeyPress={(e) => {
                if (e.key === "Enter") {
                  fetchDashboardData();
                }
              }}
            />
            <Button
              variant="contained"
              color="primary"
              size="small"
              startIcon={<SearchIcon />}
              onClick={fetchDashboardData}
            >
              جستجو
            </Button>
          </Grid>
        </Grid>
      </Grid>

      <Grid item xs={12}>
        <ResponsiveTable
          columns={[
            "ردیف",
            nameColumnLabel,
            "تعداد کل",
            "تعداد دولتی",
            "تعداد آزاد",
            "وزن کل (کیلوگرم)",
            "وزن دولتی (کیلوگرم)",
            "وزن آزاد (کیلوگرم)",
          ]}
          title={
            "داشبورد جمع مانده " + (isStewardPage ? "مباشرها" : "کشتارگاه‌ها")
          }
          data={dashboardTableData}
          paginated
          totalRows={dashboardTotalRows}
          page={dashboardPage}
          perPage={dashboardPageSize}
          handlePageChange={(newPage) => setDashboardPage(newPage)}
          handlePerRowsChange={(newPageSize) => {
            setDashboardPageSize(newPageSize);
            setDashboardPage(1);
          }}
        />
      </Grid>

      <Grid item xs={12}>
        <ResponsiveTable
          columns={[
            "ردیف",
            "تاریخ بایگانی",
            "تاریخ انبار",
            nameColumnLabel,
            isStewardPage ? "شهر مباشر" : "شهر",
            "وزن (کیلوگرم)",
            "نوع سهمیه",
            "ثبت کننده",
            "شماره تماس",
            "توضیحات",
            "عملیات",
          ]}
          title={"مانده بایگانی شده"}
          data={tableData}
          totalRows={tableTotalRows}
          page={tablePage}
          perPage={tablePageSize}
          handlePageChange={(newPage) => setTablePage(newPage)}
          handlePerRowsChange={(newPageSize) => {
            setTablePageSize(newPageSize);
            setTablePage(1);
          }}
        />
      </Grid>
    </Grid>
  );
};
