import React, { useContext, useEffect, useRef, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { useDispatch, useSelector } from "react-redux";
import { slaughterGetProductsService } from "../../services/slaughter-inventory-gets";
import InfoIcon from "@mui/icons-material/Info";
import TextField from "@mui/material/TextField";
import InputAdornment from "@mui/material/InputAdornment";
import SearchIcon from "@mui/icons-material/Search";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  Box,
  Button,
  Card,
  CardContent,
  IconButton,
  Typography,
} from "@mui/material";
import { SlaughterAddDailyList } from "../slaughter-add-daily-list/SlaughterAddDailyList";
import {
  slaughterDeleteDailyListService,
  slaughterGetPriceService,
  submitBatchAllocationsService,
} from "../../services/slaughter-add-daily-list";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import moment from "moment";
import { AppContext } from "../../../../contexts/AppContext";
import AddIcon from "@mui/icons-material/Add";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import DeleteIcon from "@mui/icons-material/Delete";
import { fixBase64 } from "../../../../utils/toBase64";
import { provincePolicyGetUploadImageService } from "../../../province/services/province-policy-upload-image";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterDailyList = () => {
  const [productsTable, setProductsTable] = useState();
  const [slaughterProducts, setSlaughterProducts] = useState();
  const [prices, setPrices] = useState([]);
  const [rendered, setrendered] = useState(false);
  const [weights, setWeights] = useState([]);
  const [data, setData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [filteredData, setFilteredData] = useState([]);
  const [rowImages, setRowImages] = useState([]);
  const [uploadPolicy, setUploadPolicy] = useState({
    killHouseAllocation: true,
  });
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [openNotif] = useContext(AppContext);

  const priceRefs = useRef([]);
  const weightRefs = useRef([]);
  const imageRefs = useRef([]);

  const dispatch = useDispatch();

  const [priceState, setPriceState] = useState({
    active: false,
    killHousePrice: 0,
    stewardPrice: 0,
    guildPrice: 0,
  });

  const getPriceByRole = () => {
    const role = getRoleFromUrl();
    if (role === "KillHouse") return priceState.killHousePrice;
    if (role === "Steward") return priceState.stewardPrice;
    if (role === "Guilds") return priceState.guildPrice;
    return 0;
  };

  useEffect(() => {
    priceRefs.current = priceRefs.current.slice(0, data?.length || 0);
    weightRefs.current = weightRefs.current.slice(0, data?.length || 0);
    imageRefs.current = imageRefs.current.slice(0, data?.length || 0);
  }, [data]);

  useEffect(() => {
    if (searchTerm) {
      const filtered = tableData.filter((item) =>
        item.some((cell) =>
          String(cell).toLowerCase().includes(searchTerm.toLowerCase())
        )
      );
      setFilteredData(filtered);
    } else {
      setFilteredData(tableData);
    }
  }, [searchTerm, tableData]);

  const handleKeyDown = (e, index, fieldType) => {
    if (e.key === "Enter") {
      e.preventDefault();

      if (fieldType === "price") {
        const updatedPrices = [...prices];
        updatedPrices[index] = Number(e.target.value.replace(/,/g, ""));
        setPrices(updatedPrices);

        if (weightRefs.current[index]) {
          weightRefs.current[index].focus();
        }
      } else if (fieldType === "weight") {
        const updatedWeights = [...weights];
        updatedWeights[index] = Number(e.target.value.replace(/,/g, ""));
        setWeights(updatedWeights);

        if (uploadPolicy?.killHouseAllocation || rowImages[index]) {
          if (imageRefs.current[index]) {
            imageRefs.current[index].focus();
          }
        } else {
          moveToNextField(index);
        }
      }
    }
  };

  const moveToNextField = (currentIndex) => {
    if (priceState?.active) {
      let nextIndex = currentIndex + 1;
      while (nextIndex < data.length) {
        if (weightRefs.current[nextIndex]) {
          weightRefs.current[nextIndex].focus();
          break;
        }
        nextIndex++;
      }

      if (nextIndex >= data.length && weightRefs.current[0]) {
        weightRefs.current[0]?.focus();
      }
    } else {
      let nextIndex = currentIndex + 1;
      while (nextIndex < data.length) {
        if (priceRefs.current[nextIndex]) {
          priceRefs.current[nextIndex].focus();
          break;
        }
        nextIndex++;
      }

      if (nextIndex >= data.length && priceRefs.current[0]) {
        priceRefs.current[0]?.focus();
      }
    }
  };

  const fetchUploadPolicy = () => {
    dispatch(
      provincePolicyGetUploadImageService({
        role_key: checkPathStartsWith("slaughter") ? selectedSubUser?.key : "",
      })
    ).then((r) => {
      if (r.payload?.data) {
        setUploadPolicy(r.payload.data);
      }
    });
  };

  const fetchPriceStatus = async () => {
    dispatch(
      slaughterGetPriceService({
        role: getRoleFromUrl(),
        role_key: selectedSubUser?.key,
      })
    ).then((r) => {
      setPriceState(r.payload.data);
    });
  };

  const fetchApiData = async () => {
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `commonly-used/?search=filter&value=&role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }&page=1&page_size=10000`
      );
      setrendered(true);
      setData(response.data.results || []);
    } catch (e) {
      console.error(e);
    } finally {
      dispatch(LOADING_END());
    }
  };

  const handleRowImageChange = (images, index) => {
    const newRowImages = [...rowImages];
    newRowImages[index] = images[0]
      ? {
          ...images[0],
          base64: fixBase64(images[0]?.data_url),
        }
      : null;
    setRowImages(newRowImages);

    if (
      (uploadPolicy?.killHouseAllocation && images[0]) ||
      !uploadPolicy?.killHouseAllocation
    ) {
      moveToNextField(index);
    }
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      const getPrice =
        parseInt(priceState?.active ? getPriceByRole() : prices[i]) *
        parseInt(weights[i]);
      return [
        i + 1,
        item?.guild?.steward ? "مباشر" : "صنف",
        `${item?.guild?.guildsName}/${item?.guild?.user?.fullname}/${item?.guild?.user?.city}/${item?.guild?.user?.mobile}`,
        item?.exclusive ? "اختصاصی" : "آزاد",
        <NumberInput
          allowLeadingZeros
          thousandSeparator=","
          key={`price-${i}`}
          size="small"
          label="قیمت"
          disabled={priceState?.active}
          value={priceState?.active ? getPriceByRole() : prices[i] || ""}
          onKeyDown={(e) => handleKeyDown(e, i, "price")}
          inputRef={(el) => (priceRefs.current[i] = el)}
          variant="outlined"
          style={{ width: 100 }}
        />,

        <NumberInput
          allowLeadingZeros
          thousandSeparator=","
          key={`weight-${i}`}
          size="small"
          label="وزن"
          value={weights[i] || ""}
          onKeyDown={(e) => {
            handleKeyDown(e, i, "weight");
          }}
          inputRef={(el) => (weightRefs.current[i] = el)}
          variant="outlined"
          style={{ width: 100 }}
        />,
        isNaN(getPrice) ? "وارد نشده! " : getPrice?.toLocaleString() + " ریال",
        <div style={{ width: 150 }} key={i}>
          <ImageUpload
            onChange={(images) => handleRowImageChange(images, i)}
            images={rowImages[i] ? [rowImages[i]] : []}
            maxNumber={1}
            title={"بارگزاری سند"}
            required={uploadPolicy?.killHouseAllocation}
            inputRef={(el) => (imageRefs.current[i] = el)}
          />
          {uploadPolicy?.killHouseAllocation && !rowImages[i] && (
            <Typography variant="caption" color="error">
              تصویر الزامی است
            </Typography>
          )}
        </div>,

        <IconButton key={i} color="error">
          <DeleteIcon onClick={() => handleDeleteItem(item.key)} />
        </IconButton>,
      ];
    });

    setTableData(d);
    setFilteredData(d);
  }, [data, prices, weights, priceState, rowImages, uploadPolicy]);

  useEffect(() => {
    fetchApiData();
    fetchPriceStatus();
    fetchUploadPolicy();
    dispatch(slaughterGetProductsService()).then((r) => {
      setSlaughterProducts(r.payload.data);
    });
  }, [selectedSubUser?.key]);

  useEffect(() => {
    const d = slaughterProducts?.map((item) => {
      return [item?.name, item?.totalRemainWeight?.toLocaleString()];
    });

    setProductsTable(d);
  }, [slaughterProducts]);

  const handleDeleteItem = (key) => {
    dispatch(slaughterDeleteDailyListService(key)).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",
        });

        fetchApiData(1);
      }
    });
  };

  const handleSendAllocate = () => {
    const filteredData = data
      ?.map((item, i) => {
        const price = priceState?.active ? getPriceByRole() : prices[i];
        const weight = weights[i];

        if (!price || !weight) return null;

        if (uploadPolicy?.killHouseAllocation && !rowImages[i]) {
          return null;
        }

        let d = {
          seller_type: "KillHouse",
          buyer_type: item?.guild?.steward ? "Steward" : "Guild",
          guild_key: !item?.guild?.steward ? item?.guild?.key : null,
          steward_key: item?.guild?.steward ? item?.guild?.key : null,
          product_key: slaughterProducts[0]?.key,
          type: "manual",
          allocation_type: item?.guild?.steward
            ? "killhouse_steward"
            : "killhouse_guild",
          number_of_carcasses: 0,
          weight_of_carcasses: weight,
          sell_type: "free",
          amount: price,
          total_amount: price * weight,
          approved_price_status: priceState?.active,
          date: moment(new Date()).format("YYYY-MM-DD"),
        };

        if (rowImages[i]) {
          d.image = rowImages[i]?.base64;
        }

        return Object.fromEntries(
          Object.entries(d).filter(([_, value]) => value !== null)
        );
      })
      .filter(Boolean);

    if (filteredData.length === 0) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "لطفا حداقل یک رکورد معتبر با عکس وارد کنید",
        severity: "error",
      });
      return;
    }

    dispatch(submitBatchAllocationsService(filteredData)).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",
        });
        setPrices([]);
        setWeights([]);
        setRowImages([]);
        fetchApiData(1);
        fetchPriceStatus();
        fetchUploadPolicy();
        dispatch(slaughterGetProductsService()).then((r) => {
          setSlaughterProducts(r.payload.data);
        });
      }
    });
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center">
      <Grid container xs={12} justifyContent="center" alignItems="center">
        <ResponsiveTable
          noPagination
          title={"موجودی انبار"}
          columns={["محصول", "مانده انبار (کیلوگرم)"]}
          data={productsTable}
          customColors={[{ name: "محصول", color: "red" }]}
        />
      </Grid>
      <Grid
        xs={12}
        container
        spacing={2}
        mt={2}
        alignItems="center"
        justifyContent="space-between"
      >
        <Grid item xs={12} md="auto">
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            sx={{ borderRadius: 3, px: 3 }}
            onClick={() => {
              dispatch(
                DRAWER({
                  right: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  content: <SlaughterAddDailyList updateTable={fetchApiData} />,
                  title: "افزودن",
                })
              );
            }}
          >
            افزودن مباشر/صنف
          </Button>
        </Grid>

        <Grid item xs={12} md>
          <Card variant="outlined" sx={{ borderRadius: 3, boxShadow: 1 }}>
            <CardContent>
              <Grid
                container
                spacing={2}
                alignItems="center"
                justifyContent="space-between"
              >
                <Grid item>
                  <Typography variant="subtitle2">
                    مجموع وزن وارد شده
                  </Typography>
                  <Typography variant="body1" color="text.secondary">
                    {weights?.length
                      ? weights.reduce((a, b) => a + b, 0).toLocaleString()
                      : "۰"}
                  </Typography>
                </Grid>

                <Grid item>
                  <Typography variant="subtitle2">وزن باقیمانده</Typography>
                  <Typography
                    variant="body1"
                    color={
                      weights?.length && slaughterProducts
                        ? weights?.reduce((a, b) => a + b, 0) >
                          slaughterProducts[0]?.totalRemainWeight
                          ? "error"
                          : "text.secondary"
                        : "text.secondary"
                    }
                  >
                    {slaughterProducts?.[0]?.totalRemainWeight !== undefined
                      ? weights?.length
                        ? (
                            slaughterProducts[0]?.totalRemainWeight -
                            weights.reduce((a, b) => a + b, 0)
                          ).toLocaleString()
                        : slaughterProducts[0]?.totalRemainWeight.toLocaleString()
                      : "۰"}
                  </Typography>
                </Grid>

                <Grid item>
                  <Button
                    variant="contained"
                    color="success"
                    startIcon={<CheckCircleIcon />}
                    sx={{ borderRadius: 3, px: 3 }}
                    onClick={handleSendAllocate}
                    disabled={
                      weights.length
                        ? weights.reduce((a, b) => a + b, 0) >
                            slaughterProducts[0]?.totalRemainWeight ||
                          (uploadPolicy?.killHouseAllocation &&
                            data.some(
                              (_, i) =>
                                prices[i] &&
                                weights[i] &&
                                (!rowImages[i] || !rowImages[i].base64)
                            ))
                        : true
                    }
                  >
                    ثبت
                  </Button>
                </Grid>
              </Grid>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      <Grid container xs={12} mt={2} gap={1} sx={{ userSelect: "none" }}>
        <InfoIcon color="error" />
        <Typography variant="body1" color="error">
          پس از وارد کردن هر مقدار، کلید Enter را فشار دهید!
        </Typography>
      </Grid>

      <Grid container xs={12} mt={2} gap={1} sx={{ userSelect: "none" }}>
        <InfoIcon color="primary" />
        <Typography variant="body1" color="primary">
          صرفا تخصیصاتی که هر دو مقدار قیمت و وزن آنها را وارد کنید ثبت خواهند
          شد.
        </Typography>
      </Grid>

      <Grid container xs={12} mt={2}>
        <TextField
          fullWidth
          variant="outlined"
          placeholder="جستجو..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
          }}
          sx={{ mb: 2 }}
        />
      </Grid>

      {filteredData?.length ? (
        <Grid container xs={12} gap={1} mt={2} mb={2}>
          {filteredData?.map((item, i) => (
            <Grid
              container
              xs={12}
              key={i}
              sx={{
                p: 2,
                pl: 5,
                borderRadius: 2,
                backgroundColor: i % 2 === 0 ? "#fef6f0" : "#ffffff",
                boxShadow: "0 2px 6px rgba(0,0,0,0.05)",
                position: "relative",
                flexDirection: "row",
                gap: 2,
                alignItems: "center",
              }}
            >
              <Box
                sx={{
                  position: "absolute",
                  top: 12,
                  left: 12,
                  backgroundColor: "#fb8c00",
                  width: 28,
                  height: 28,
                  borderRadius: "50%",
                  color: "#fff",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: "0.8rem",
                  fontWeight: 700,
                  boxShadow: "0 1px 4px rgba(0,0,0,0.2)",
                }}
              >
                {item[0]}
              </Box>

              <Grid
                item
                sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
              >
                <Typography
                  variant="caption"
                  color="text.secondary"
                  sx={{ minWidth: 64 }}
                >
                  ماهیت:
                </Typography>
                <Typography variant="body2" fontSize="0.8rem">
                  {item[1]}
                </Typography>
              </Grid>

              <Grid
                item
                sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
              >
                <Typography
                  variant="caption"
                  color="text.secondary"
                  sx={{ minWidth: 64 }}
                >
                  خریدار:
                </Typography>
                <Typography variant="body2" fontSize="0.8rem">
                  {item[2]}
                </Typography>
              </Grid>

              <Grid
                item
                sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
              >
                <Typography
                  variant="caption"
                  color="text.secondary"
                  sx={{ minWidth: 64 }}
                >
                  نوع فروش:
                </Typography>
                <Typography variant="body2" fontSize="0.8rem">
                  {item[3]}
                </Typography>
              </Grid>

              <Grid
                item
                sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
              >
                <Typography variant="caption" color="text.secondary">
                  قیمت هرکیلو:
                </Typography>
                <Typography variant="body2" fontSize="0.8rem">
                  {item[4]}
                </Typography>
              </Grid>

              <Grid
                item
                sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
              >
                <Typography variant="caption" color="text.secondary">
                  وزن لاشه:
                </Typography>
                <Typography variant="body2" fontSize="0.8rem">
                  {item[5]}
                </Typography>
              </Grid>

              <Grid
                item
                sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
              >
                <Typography
                  variant="caption"
                  color="text.secondary"
                  sx={{ minWidth: 64 }}
                >
                  قیمت کل:
                </Typography>
                <Typography variant="body2" fontSize="0.8rem">
                  {item[6]}
                </Typography>
              </Grid>

              <Grid
                item
                sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
              >
                {item[7]}
              </Grid>

              <Grid
                item
                sx={{ display: "flex", alignItems: "center", gap: 0.5 }}
              >
                {item[8]}
              </Grid>

              <Grid item>
                {!priceState?.active &&
                  (!prices[i] || !weights[i]) &&
                  (prices[i] || weights[i]) && (
                    <Typography variant="caption" color="error">
                      لطفا همه موارد را وارد کنید و کلید Enter را بزنید
                    </Typography>
                  )}
              </Grid>
            </Grid>
          ))}
        </Grid>
      ) : (
        <Typography mt={4}>
          {!rendered
            ? searchTerm
              ? "نتیجه‌ای یافت نشد"
              : "در حال بارگزاری..."
            : "موردی یافت نشد!"}
        </Typography>
      )}
    </Grid>
  );
};
