import { useCallback, useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  Button,
  Box,
  Typography,
  TextField,
  FormControlLabel,
  Switch,
} from "@mui/material";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { SPACING } from "../../../../data/spacing";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { resizeImage } from "../../../../utils/resizeImage";
import { fixBase64 } from "../../../../utils/toBase64";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceWarehouseArchive } from "../../services/province-warehouse-archive";
import { provinceGetTotalKillhouseRemainWeight } from "../../services/province-get-total-killhouse-remain-weight";
import { useLocation } from "react-router-dom";
import { formatJustDate } from "../../../../utils/formatTime";

const DayDetailContent = ({
  killhouseName,
  killhouseKey,
  dayData,
  governmentalData,
  freeData,
  selectedType,
  onSuccess,
}) => {
  const dispatch = useDispatch();
  const location = useLocation();
  const [openNotif] = useContext(AppContext);

  const [description, setDescription] = useState("");
  const [profileImages, setProfileImages] = useState([]);
  const [profileImg, setProfileImg] = useState("");

  const currentData = selectedType === "free" ? freeData : governmentalData;

  const getArchiveType = () => {
    const pathSegments = location.pathname.split("/").filter(Boolean);
    if (pathSegments.includes("steward")) {
      return "steward";
    }
    if (pathSegments.includes("killhouse")) {
      return "kill_house";
    }
    return pathSegments[pathSegments.length - 1] || "kill_house";
  };

  const imageHandler = (imageList) => {
    setProfileImages(imageList);
    if (imageList[0]) {
      const file = imageList[0]?.file;
      resizeImage(file, (resizedDataUrl) => {
        const optimizedBase64 = fixBase64(resizedDataUrl);
        setProfileImg(optimizedBase64);
      });
    } else {
      setProfileImg("");
    }
  };

  const handleSubmit = () => {
    const archiveType = getArchiveType();
    const role = getRoleFromUrl();

    const payload = {
      role,
      owner_key: killhouseKey,
      archive_type: archiveType,
      date: dayData,
      weight: currentData.amount,
      quota: selectedType,
      image: profileImg || "",
      description: description || "",
    };

    dispatch(provinceWarehouseArchive(payload)).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",
        });

        dispatch(
          DRAWER({
            top: false,
            left: false,
            bottom: false,
            right: false,
            title: null,
            content: null,
            size: null,
          })
        );
        setDescription("");
        setProfileImg("");
        setProfileImages([]);

        if (onSuccess) {
          onSuccess();
        }
      }
    });
  };

  return (
    <Grid container gap={2}>
      <Grid item xs={12}>
        <Typography variant="h6" color="primary" gutterBottom>
          {killhouseName}
        </Typography>
        <Typography variant="body2" color="text.secondary">
          تاریخ: {formatJustDate(dayData)}
        </Typography>
      </Grid>

      <Grid item xs={12}>
        <Box
          sx={{
            padding: 2,
            backgroundColor: selectedType === "free" ? "#e8f5e9" : "#e3f2fd",
            borderRadius: 2,
            mt: 1,
            border: `2px solid ${
              selectedType === "free" ? "#2e7d32" : "#1565c0"
            }`,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <Typography
            variant="subtitle2"
            gutterBottom
            fontWeight="bold"
            sx={{
              color: selectedType === "free" ? "#2e7d32" : "#1565c0",
            }}
          >
            موجودی {selectedType === "free" ? "آزاد" : "دولتی"}:
          </Typography>
          <Typography variant="h6" fontWeight="600">
            {currentData.amount.toLocaleString()} کیلوگرم
          </Typography>
        </Box>
      </Grid>

      <Grid item xs={12}>
        <ImageUpload
          onChange={imageHandler}
          images={profileImages}
          maxNumber={1}
          title="بارگذاری سند"
        />
      </Grid>

      <Grid item xs={12}>
        <TextField
          fullWidth
          multiline
          rows={5}
          label="توضیحات"
          variant="outlined"
          value={description}
          onChange={(e) => {
            setDescription(e.target.value);
          }}
          placeholder="توضیحات خود را وارد کنید..."
        />
      </Grid>
      <Grid item xs={12}>
        <Button
          variant="contained"
          color="primary"
          fullWidth
          onClick={handleSubmit}
          disabled={!description.trim()}
        >
          ثبت بایگانی
        </Button>
      </Grid>
    </Grid>
  );
};

export const ProvinceDispensersStockSlugActive = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const location = useLocation();
  const pathSegments = location.pathname.split("/").filter(Boolean);
  const lastSegment = pathSegments[pathSegments.length - 1] || "";
  const isStewardPage = lastSegment === "steward";
  const nameColumnLabel = isStewardPage ? "مباشر" : "کشتارگاه";
  const [tableData, setTableData] = useState([]);
  const [killhousesData, setKillhousesData] = useState([]);
  const [showType, setShowType] = useState("governmental");
  const initialPageSize = isStewardPage ? 40 : 10;
  const [tablePage, setTablePage] = useState(1);
  const [tablePageSize, setTablePageSize] = useState(initialPageSize);
  const [tableTotalRows, setTableTotalRows] = useState(0);

  const handleTypeToggle = () => {
    setShowType((prev) => (prev === "free" ? "governmental" : "free"));
  };

  const fetchKillhouseData = useCallback(() => {
    const params = {
      search: "filter",
      value: "",
      page: tablePage,
      page_size: tablePageSize,
      quota: showType === "free" ? "free" : "governmental",

      ...(isStewardPage ? { owner_type: "steward" } : {}),
    };

    dispatch(provinceGetTotalKillhouseRemainWeight(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 transformedData = apiData
          .filter((item) => item.info !== null)
          .map((item) => ({
            id: item.key,
            key: item.key,
            name: isStewardPage ? item.guildsName || item.name : item.name,
            governmental: item.info?.governmental || [],
            free: item.info?.free || [],
          }));

        setKillhousesData(transformedData);
      }
    });
  }, [dispatch, openNotif, isStewardPage, tablePage, tablePageSize, showType]);

  useEffect(() => {
    setTablePage(1);
    setTablePageSize(isStewardPage ? 40 : 10);
  }, [isStewardPage]);

  useEffect(() => {
    fetchKillhouseData();
  }, [fetchKillhouseData]);

  useEffect(() => {
    const filteredKillhouses = killhousesData
      .map((killhouse) => {
        const relevantList =
          showType === "free" ? killhouse.free : killhouse.governmental;
        const nonZeroDays = Array.isArray(relevantList)
          ? relevantList.filter((item) => item?.amount)
          : [];

        if (!nonZeroDays.length) {
          return null;
        }

        const totalWeight = nonZeroDays.reduce(
          (acc, curr) => acc + (curr?.amount || 0),
          0
        );

        return { killhouse, nonZeroDays, totalWeight };
      })
      .filter(Boolean);

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

    const data = filteredKillhouses.map((item, index) => {
      const { killhouse, nonZeroDays, totalWeight } = item;
      const uniqueDays = [...new Set(nonZeroDays.map((d) => d.day))].sort();

      const daysContent = (
        <Box
          key={`days-${killhouse.id}`}
          sx={{
            display: "flex",
            gap: 1,
            flexWrap: "wrap",
            alignItems: "center",
            width: "100%",
            justifyContent: "flex-start",
          }}
        >
          {uniqueDays
            .map((day, dayIndex) => {
              const govDay = killhouse.governmental.find((d) => d.day === day);
              const freeDay = killhouse.free.find((d) => d.day === day);

              const currentAmount =
                showType === "free"
                  ? freeDay?.amount || 0
                  : govDay?.amount || 0;

              if (!currentAmount) {
                return null;
              }

              return (
                <Button
                  key={`day-${dayIndex}-${day}`}
                  variant="outlined"
                  size="small"
                  onClick={() => {
                    dispatch(
                      DRAWER({
                        right: !(window.innerWidth <= 600),
                        bottom: window.innerWidth <= 600,
                        size: 360,
                        title: `جزئیات موجودی - ${formatJustDate(day)}`,
                        content: (
                          <DayDetailContent
                            killhouseName={killhouse.name}
                            killhouseKey={killhouse.key}
                            dayData={day}
                            governmentalData={govDay || { day, amount: 0 }}
                            freeData={freeDay || { day, amount: 0 }}
                            selectedType={showType}
                            onSuccess={fetchKillhouseData}
                          />
                        ),
                      })
                    );
                  }}
                  sx={{
                    minWidth: 90,
                    minHeight: 42,
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    justifyContent: "center",
                    padding: "2px 8px",
                    backgroundColor: "#e3f2fd",
                    borderColor: "primary.main",
                    "&:hover": {
                      backgroundColor: "#bbdefb",
                    },
                  }}
                >
                  <Typography
                    variant="caption"
                    sx={{
                      fontSize: { xs: "11px", md: "14px" },
                      color: "text.secondary",
                      marginBottom: "0px",
                    }}
                  >
                    {formatJustDate(day)}
                  </Typography>
                  <Typography
                    variant="caption"
                    sx={{
                      fontSize: { xs: "11px", md: "13px" },
                      color: showType === "free" ? "#2e7d32" : "#1565c0",
                      fontWeight: 600,
                    }}
                  >
                    {showType === "free" ? "آزاد" : "دولتی"}:{" "}
                    {currentAmount.toLocaleString()}
                  </Typography>
                </Button>
              );
            })
            .filter(Boolean)}
        </Box>
      );

      return [
        (tablePage - 1) * tablePageSize + index + 1,
        killhouse.name || "نامشخص",
        totalWeight.toLocaleString(),
        daysContent,
      ];
    });

    setTableData(data);
  }, [
    showType,
    killhousesData,
    fetchKillhouseData,
    dispatch,
    tablePage,
    tablePageSize,
    tableTotalRows,
  ]);

  return (
    <Grid container spacing={2} px={2} mt={SPACING.SMALL}>
      <Grid item xs={12}>
        <Box
          sx={{
            display: "flex",
            alignItems: "flex-start",
            flexDirection: "column",
            justifyContent: "space-between",
            mb: 2,
          }}
        >
          <Grid>
            <FormControlLabel
              control={
                <Switch
                  checked={showType === "free"}
                  onChange={handleTypeToggle}
                  color="primary"
                />
              }
              label={
                <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                  <Typography
                    variant="body2"
                    sx={{
                      color: showType === "governmental" ? "#1565c0" : "#666",
                      fontWeight: showType === "governmental" ? 600 : 400,
                    }}
                  >
                    دولتی
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    /
                  </Typography>
                  <Typography
                    variant="body2"
                    sx={{
                      color: showType === "free" ? "#2e7d32" : "#666",
                      fontWeight: showType === "free" ? 600 : 400,
                    }}
                  >
                    آزاد
                  </Typography>
                </Box>
              }
              labelPlacement="start"
            />
          </Grid>
        </Box>
      </Grid>
      <Grid item xs={12}>
        <ResponsiveTable
          title={"مانده فعال" + " " + (showType === "free" ? "آزاد" : "دولتی")}
          columns={[
            "ردیف",
            nameColumnLabel,
            `کل مانده ${showType === "free" ? "آزاد" : "دولتی"} (کیلوگرم)`,
            "روزها",
          ]}
          data={tableData}
          totalRows={tableTotalRows}
          page={tablePage}
          perPage={tablePageSize}
          handlePageChange={(newPage) => setTablePage(newPage)}
          handlePerRowsChange={(newPageSize) => {
            setTablePageSize(newPageSize);
            setTablePage(1);
          }}
        />
      </Grid>
    </Grid>
  );
};
