import { useDispatch, useSelector } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { useContext, useEffect, useState } from "react";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { CheckCleanceCode } from "../../../../components/check-clearance-code/ChechClearanceCode";
import { Grid } from "../../../../components/grid/Grid";
import { StewardDispenserSaleOutDashboard } from "../../../guild/components/StewardDispenserSaleOutDashboard";
import { DatePicker } from "@mui/x-date-pickers";
import {
  Autocomplete,
  Button,
  FormControl,
  TextField,
  Tooltip,
} from "@mui/material";
import moment from "moment";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { provinceDispenserWithOutGetDashboard } from "../../services/province-deispenser-sale-out-get-dashboard";
import { provinceDispenserGetStewardService } from "../../services/province-dispenser-get-steward";
import { ProvinceDispenserStewardSaleOutOperation } from "../province-dispenser-steward-sale-out-operation/ProvinceDispenserStewardSaleOutOperation";

export const ProvinceDispenserSaleOut = ({ priceInfo }) => {
  const { slaughterProducts } = useSelector(
    (state) => state.slaughterSlice || {}
  );
  const dispatch = useDispatch();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

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

  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 [dashboardData, setDashboardData] = useState([]);
  const [steward, setSteward] = useState([]);
  const [selectedSteward, setselectedSteward] = useState(null);

  const userKey = useSelector((state) => state.userSlice?.userProfile?.key);
  const [openNotif] = useContext(AppContext);
  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `steward_free_sale_bar/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${
          page || 1
        }&page_size=${perPage}&type=dashboard${
          selectedSteward
            ? `&steward_key=${selectedSteward}`
            : "&steward_key=all"
        }`
      );
      setData(response.data?.results || []);
      setTotalRows(response.data?.count || 0);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      dispatch(LOADING_END());
    }
  };
  const fetchsteward = () => {
    dispatch(provinceDispenserGetStewardService()).then((r) => {
      setSteward(r?.payload?.data || []);
    });
  };
  const fetchDashboardData = () => {
    dispatch(
      provinceDispenserWithOutGetDashboard({
        search: "filter",
        role: getRoleFromUrl(),
        selectedDate1,
        selectedDate2,
        steward_key: selectedSteward || "all",
      })
    ).then((r) => {
      setDashboardData(r?.payload?.data || []);
    });
  };
  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

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

  useEffect(() => {
    const d = Array.isArray(data)
      ? 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,
            `${item?.steward?.guildsName?.toLocaleString()} ${item?.steward?.user?.fullname?.toLocaleString()} ${
              item?.steward?.user?.mobile?.toLocaleString() || "-"
            }`,
            `${item?.buyerName} (${item?.buyerMobile})`,
            item?.buyer ? `${item?.buyer?.unitName}` : `${item?.buyerName}`,
            item?.province,
            item?.city,
            item?.clearanceCode && (
              <CheckCleanceCode clearanceCode={item?.clearanceCode} />
            ),
            item?.quarantineWeightOfCarcasses?.toLocaleString(),
            item?.weightOfCarcasses?.toLocaleString(),
            <ProvinceDispenserStewardSaleOutOperation
              fetchDashboardData={fetchDashboardData}
              item={item}
              key={i}
              fetchApiData={fetchApiData}
              priceInfo={priceInfo}
              remainWeight={slaughterProducts[0]?.totalRemainWeight || 0}
            />,
          ];
        })
      : [];
    setTableData(d);
  }, [data, page, perPage, priceInfo, slaughterProducts]);
  useEffect(() => {
    fetchApiData(1);
    fetchDashboardData();
    fetchsteward();
  }, [dispatch, selectedDate1, selectedDate2, perPage, selectedSteward]);

  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={4}
      >
        <Grid container width="100%" isDashboard>
          <StewardDispenserSaleOutDashboard
            dashboardData={dashboardData}
            fetchDashboardData={fetchDashboardData}
          />
        </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 }}>
                <Autocomplete
                  options={steward}
                  getOptionLabel={(option) =>
                    `(${option?.guildsName}) ${option?.user?.fullname}`
                  }
                  value={
                    selectedSteward && Array.isArray(steward)
                      ? steward.find((item) => item?.key === selectedSteward) ||
                        null
                      : null
                  }
                  onChange={(event, newValue) => {
                    setselectedSteward(newValue ? newValue.key : null);
                  }}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="مباشرین"
                      size="small"
                      placeholder="جستجوی مباشرین"
                    />
                  )}
                  noOptionsText="مباشری یافت نشد"
                  isOptionEqualToValue={(option, value) =>
                    option?.key === value?.key
                  }
                />
              </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_free_sale_out_province_excel/?role=${getRoleFromUrl()}&key=${userKey}&search=filter&value=${textValue} &date1=${selectedDate1}&date2=${selectedDate2}&type=Steward`;
                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>
  );
};
