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 } from "../../../../utils/formatTime";
import { RiSearchLine } from "react-icons/ri";
import { ProvinceDispenserSaleOutDashboard } from "../province-dispenser-sale-out-dashboard/ProvinceDispenserSaleOutDashboard";
import { CheckCleanceCode } from "../../../../components/check-clearance-code/ChechClearanceCode";
import { provinceDispenserWithOutGetDashboard } from "../../services/province-dispenser-sale-out-dashboard";
import { AppContext } from "../../../../contexts/AppContext";
import { ProvinceDispenserSaleOutOperation } from "../province-dispenser-sale-out-operation/ProvinceDispenserSaleOutOperation";
import { RiFileExcel2Fill } from "react-icons/ri";
import { provinceDispenserGetKillHouseService } from "../../services/province-dispenser-get-kill-house";

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

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `kill_house_free_sale_bar/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${
          page || 1
        }&page_size=${perPage}&type=dashboard${
          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 fetchDashboardData = () => {
    dispatch(
      provinceDispenserWithOutGetDashboard({
        search: "filter",
        role: getRoleFromUrl(),
        selectedDate1,
        selectedDate2,
      })
    ).then((r) => {
      setDashboardData(r.payload?.data);
    });
  };

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        formatJustDate(item?.date) || "-",
        `${item?.killHouse?.killHouseOperator?.user?.fullname} ${
          item?.killHouse?.name
        } ${item?.killHouse?.killHouseOperator?.user?.mobile || "-"}`,
        `${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(),
        <ProvinceDispenserSaleOutOperation
          item={item}
          key={i}
          fetchApiData={fetchApiData}
          fetchDashboardData={fetchDashboardData}
          priceInfo={priceInfo}
        />,
      ];
    });
    setTableData(d);
  }, [data, page, perPage, priceInfo]);

  const fetchKillHouses = () => {
    dispatch(provinceDispenserGetKillHouseService()).then((r) => {
      setKillHouses(r.payload.data);
    });
  };
  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };
  useEffect(() => {
    fetchApiData(1);
    fetchDashboardData();
    fetchKillHouses();
  }, [dispatch, selectedDate1, selectedDate2, perPage, selectedKillHouse]);

  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>
          <ProvinceDispenserSaleOutDashboard
            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 }}>
                <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
                }free_sale_out_province_excel/?role=${getRoleFromUrl()}&key=${userKey}&search=filter&value=${textValue} &date1=${selectedDate1}&date2=${selectedDate2}&type`;
                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>
  );
};
