import React, { useContext, useEffect, useState } from "react";
import { Button, TextField } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch } from "react-redux";
import axios from "axios";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { useParams } from "react-router-dom";
import { formatJustDate } from "../../../../utils/formatTime";
import { slaughterGetDispenserDashboardService } from "../../services/slaughter-house-get-dispenser-dashboard-service";
import { RiSearchLine } from "react-icons/ri";

export const SlaughterHouseDispenserDetails = () => {
  const { key } = useParams();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const dispatch = useDispatch();
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  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 fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `dispenser-allocations/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&dispenser_key=${key}`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

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

  //   const updateTable = () => {
  //     fetchApiData(page !== 0 ? page : 1);
  //   };

  useEffect(() => {
    fetchApiData(1);
  }, []);

  useEffect(() => {
    dispatch(
      slaughterGetDispenserDashboardService({
        date1: selectedDate1,
        date2: selectedDate2,
        key: key,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  }, [selectedDate1, selectedDate2]);

  const getDispenserType = (item) => {
    let type = "";
    switch (item?.dispenser?.dispenserType) {
      case "inductor":
        type = "واسطه";
        break;
      case "salesman":
        type = "فروشنده";
        break;
      case "driver":
        type = `راننده - ${item?.dispenser?.car} (${item?.dispenser?.pelak})`;
        break;
      default:
        break;
    }

    return type;
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      let sellType, sellerType;
      if (item.sellerType === "guilds") {
        sellerType = "صنف";
      } else if (item.sellerType === "steward") {
        sellerType = "مباشر";
      }

      if (item.sellType === "free") {
        sellType = "آزاد";
      } else {
        if (item.type === "manual") {
          sellType = "اختصاصی (دستی)";
        } else {
          sellType = "اختصاصی (اتوماتیک)";
        }
      }

      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.dispenser?.user?.fullname} (${item?.dispenser?.user?.mobile})`,
        getDispenserType(item),
        item?.guilds ? item?.guilds?.guildsId : item?.steward?.guilds?.guildsId,
        formatJustDate(item.date),
        sellerType,
        sellType,
        item?.guilds
          ? item?.guilds?.guildsName
          : item?.steward?.guilds?.guildsName,
        item?.guilds
          ? item?.guilds?.user.fullname
          : item?.steward?.guilds?.user.fullname,
        item?.guilds
          ? item?.guilds?.user.nationalId
          : item?.steward?.guilds?.user.nationalId,
        item?.guilds
          ? item?.guilds?.user.mobile
          : item?.steward?.guilds?.user.mobile,
        item?.guilds
          ? item?.guilds?.typeActivity
          : item?.steward?.guilds?.typeActivity,
        item?.guilds
          ? item?.guilds?.areaActivity
          : item?.steward?.guilds?.areaActivity,
        item?.guilds
          ? item?.guilds?.licenseNumber
          : item?.steward?.guilds?.licenseNumber,
        item?.guilds
          ? item?.guilds?.user?.city?.name
          : item?.steward?.guilds?.user?.city?.name,
        item?.numberOfCarcasses,
        item?.weightOfCarcasses,
        item?.loggedRegistrationCode ? item.loggedRegistrationCode : "-",
        item?.receiverState === "accepted"
          ? "تایید شده"
          : item?.receiverState === "rejected"
          ? "رد شده"
          : "در انتظار تایید",
      ];
    });

    setTableData(d);
  }, [data]);

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `dispenser-allocations/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}&dispenser_key=${key}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Grid>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} size="small" />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} size="small" />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>
      <Grid container xs={12} justifyContent="start" alignItems="center">
        <ResponsiveTable
          noPagination
          data={[
            [
              dashboardData?.numberOfAllocations?.toLocaleString(),
              dashboardData?.totalQuantity?.toLocaleString(),
              dashboardData?.totalWeight?.toLocaleString(),
              dashboardData?.numberOfStewardsAllocations?.toLocaleString(),
              dashboardData?.stewardTotalQuantity?.toLocaleString(),
              dashboardData?.stewardTotalWeight?.toLocaleString(),
              dashboardData?.numberOfGuildsAllocations?.toLocaleString(),
              dashboardData?.guildTotalQuantity?.toLocaleString(),
              dashboardData?.guildTotalWeight?.toLocaleString(),
            ],
          ]}
          columns={[
            "تعداد کل تخصیصات",
            "حجم کل تخصیصات",
            "وزن کل تخصیصات",
            "تعداد مباشرین تختصیص داده شده",
            "حجم تخصیصی به مباشرین",
            "وزن تخصیصی به مباشرین",
            "تعداد اصناف تختصیص داده شده",
            "حجم تخصیصی به اصناف",
            "وزن تخصیصی به اصناف",
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>

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