import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { useDispatch, useSelector } from "react-redux";
import {
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Tooltip,
} from "@mui/material";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import moment from "moment";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import axios from "axios";
import { DatePicker } from "@mui/x-date-pickers";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { RiSearchLine } from "react-icons/ri";
import { ProvinceDispenserSaleWithInInventory } from "../province-dispenser-sale-with-in-province-inventory/ProvinceDispenserSaleWithInInventory";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceDispenserWithInGetDashboard } from "../../services/province-dispenser-with-in-sale-inventory-dashboard";
import { ProvinceDispenserSaleWithInProvinceOperation } from "../province-dispenser-sale-with-in-province-operation/ProvinceDispenserSaleWithInProvinceOperation";
import { RiFileExcel2Fill } from "react-icons/ri";
import { provinceDispenserGetKillHouseService } from "../../services/province-dispenser-get-kill-house";
import ShowImage from "../../../../components/show-image/ShowImage";
import { getAllocationType } from "../../../../utils/getAllocationType";

export const ProvinceDispenserAcceptedSaleWithInProvince = ({ priceInfo }) => {
  const dispatch = useDispatch();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [dashboardData, setDashboardData] = useState([]);
  const [openNotif] = useContext(AppContext);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  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 [killHouses, setKillHouses] = useState([]);
  const [selectedKillHouse, setSelectedKillHouse] = useState(null);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `/in-province-allocation/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&trash=false&page=${
          page || 1
        }&page_size=${perPage}&type=KillHouse${
          selectedKillHouse
            ? `&kill_house_key=${selectedKillHouse}`
            : "&kill_house_key=all"
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      dispatch(LOADING_END());
    }
  };
  const fetchKillHouses = () => {
    dispatch(provinceDispenserGetKillHouseService()).then((r) => {
      setKillHouses(r.payload.data);
    });
  };
  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  const getAllocationData = (item) => {
    if (!item) return "-";

    switch (item?.allocationType) {
      case "killhouse_killhouse":
        return `${item?.toKillHouse?.name || "-"} - ${
          item?.toKillHouse?.killHouseOperator?.user?.fullname || "-"
        } (${item?.toKillHouse?.killHouseOperator?.user?.mobile || "-"})`;
      case "killhouse_steward":
        return `${item?.toStewards?.name || "-"} - ${
          item?.toStewards?.user?.fullname || "-"
        } (${item?.toStewards?.user?.mobile || "-"})`;
      case "killhouse_guild":
        return `${item?.toGuilds?.guildsName || "-"} - ${
          item?.toGuilds?.user?.fullname || "-"
        } (${item?.toGuilds?.user?.mobile || "-"})`;
      case "ColdHouse":
        return `${item?.toColdHouse?.name || "-"}`;
      default:
        return `${item?.toKillHouse?.name || "-"} - ${
          item?.toKillHouse?.killHouseOperator?.user?.fullname || "-"
        } (${item?.toKillHouse?.killHouseOperator?.user?.mobile || "-"})`;
    }
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const fetchDashboardData = () => {
    dispatch(
      provinceDispenserWithInGetDashboard({
        search: "filter",
        role: getRoleFromUrl(),
        selectedDate1,
        selectedDate2,
        kill_house_key: selectedKillHouse || "all",
        trash: false,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.date ? formatTime(item?.date) : "-",
        item?.productionDate ? formatJustDate(item?.productionDate) : "-",
        item?.distributionType === "web"
          ? "سایت"
          : item?.distributionType === "app"
          ? "موبایل"
          : item?.distributionType === "pos"
          ? "پوز"
          : item?.distributionType,
        getAllocationType(item),
        `${item?.killHouse?.killHouseOperator?.user?.fullname?.toLocaleString()} ${item?.killHouse?.name?.toLocaleString()} ${
          item?.killHouse?.killHouseOperator?.user?.mobile?.toLocaleString() ||
          "-"
        }`,
        getAllocationData(item),
        item?.sellType === "exclusive" ? "اختصاصی" : "آزاد",
        item?.quota === "governmental"
          ? "دولتی"
          : item?.quota === "free"
          ? "آزاد"
          : "-",
        item?.approvedPriceStatus ? "دولتی" : "آزاد",
        (item?.amount?.toLocaleString() || "0") + " ریال",
        (item?.totalAmount?.toLocaleString() || "0") + " ریال",
        item?.weightOfCarcasses?.toLocaleString() || "0",
        item?.reciverWeightOfCarcasses?.toLocaleString() || "0",
        item?.loggedRegistrationCode || "-",
        item?.registrationCode ? "ارسال شده" : "ارسال نشده",
        <ShowImage key={i} src={item?.image} />,
        item?.receiverState === "accepted" || item?.loggedRegistrationCode
          ? "تایید شده"
          : item?.receiverState === "rejected"
          ? "رد شده"
          : item?.activeExpireDateTime && !item?.loggedRegistrationCode
          ? "در انتظار ورود کد احراز"
          : "در انتظار تایید",
        <ProvinceDispenserSaleWithInProvinceOperation
          item={item}
          key={i}
          fetchApiData={fetchApiData}
          priceInfo={priceInfo}
          fetchDashboardData={fetchDashboardData}
          isAccepted
        />,
      ];
    });
    setTableData(d);
  }, [data, page, perPage, priceInfo]);

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

  useEffect(() => {
    fetchKillHouses();
  }, [dispatch]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    fetchApiData(1);
    fetchDashboardData();
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center">
      <Grid
        container
        xs={12}
        justifyContent="center"
        alignItems="center"
        gap={2}
        mt={2}
      >
        <Grid container width="100%" isDashboard>
          <ProvinceDispenserSaleWithInInventory dashboardData={dashboardData} />
        </Grid>
        <Grid
          container
          xs={12}
          justifyContent="start"
          alignItems="center"
          gap={2}
        >
          <Grid>
            <DatePicker
              label="از تاریخ"
              renderInput={(params) => (
                <TextField
                  {...params}
                  style={{ width: "160px" }}
                  size="small"
                />
              )}
              value={selectedDate1}
              onChange={(newValue) => {
                setSelectedDate1(moment(newValue).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              label="تا تاریخ"
              renderInput={(params) => (
                <TextField
                  {...params}
                  style={{ width: "160px" }}
                  size="small"
                />
              )}
              value={selectedDate2}
              onChange={(newValue) => {
                setSelectedDate2(moment(newValue).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <form onSubmit={handleSubmit} style={{ marginRight: "16px" }}>
              <FormControl size="small" style={{ width: 200 }}>
                <InputLabel id="killhouse-select-label">کشتارگاه</InputLabel>
                <Select
                  labelId="killhouse-select-label"
                  value={selectedKillHouse || "all"}
                  onChange={(e) =>
                    setSelectedKillHouse(
                      e.target.value === "all" ? null : e.target.value
                    )
                  }
                  label="کشتارگاه"
                >
                  <MenuItem value="all">همه کشتارگاه‌ها</MenuItem>
                  {killHouses.map((item) => (
                    <MenuItem key={item.key} value={item.key}>
                      {item.shopType} {item.shopName}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>

              <TextField
                id="outlined-basic"
                size="small"
                label="جستجو"
                variant="outlined"
                style={{ width: 250, marginRight: "16px" }}
                onChange={handleTextChange}
                value={textValue}
              />
              <Button type="submit" endIcon={<RiSearchLine />}>
                جستجو
              </Button>
            </form>
          </Grid>
          <Tooltip title="خروجی اکسل">
            <Button
              color="success"
              onClick={() => {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                  severity: "success",
                });
                const link = `${
                  axios.defaults.baseURL
                }steward_allocation_excel/?role=${getRoleFromUrl()}&key=${userKey}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&trash=false&type=KillHouse${
                  selectedKillHouse
                    ? `&kill_house_key=${selectedKillHouse}`
                    : "&kill_house_key=all"
                }`;
                window.location.href = link;
              }}
            >
              <RiFileExcel2Fill size={32} />
            </Button>
          </Tooltip>
        </Grid>

        <ResponsiveTable
          data={tableData}
          columns={[
            "ردیف",
            "تاریخ ثبت",
            "تاریخ تولید گوشت",
            "ثبت شده",
            "نوع تخصیص",
            "مشخصات فروشنده",
            "مشخصات خریدار",
            "فروش",
            "سهمیه",
            "نوع فروش",
            "قیمت هر کیلو",
            "قیمت کل",
            "وزن تخصیصی",
            "وزن تایید شده",
            "کداحراز",
            "وضعیت کد احراز",
            "سند",
            "وضعیت",
            "عملیات",
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title="تخصیصات صورت گرفته"
        />
      </Grid>
    </Grid>
  );
};
