import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Button, Chip, Tab, Tabs, TextField, Tooltip } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { ProvinceFreeSaleNewRequest } from "../../../aviculture/components/province-free-sale-new-request/ProvinceFreeSaleNewRequest";
import { SPACING } from "../../../../data/spacing";
import { useDispatch, useSelector } from "react-redux";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate } from "../../../../utils/formatTime";
import { ProvinceFreeSalesAcceptedRequests } from "../province-free-sales-accepted-requests/ProvinceFreeSalesAcceptedRequests";
import { ProvinceFreeSalsesManageBuyers } from "../province-free-sales-manage-buyers/ProvinceFreeSalsesManageBuyers";
import { provinceApproveFreeSaleService } from "../../services/province-approve-free-sale";
import { ProvinceFreeSalesOperations } from "../province-free-sales-operations/ProvinceFreeSalesOperations";
import { avicultureGetWageType } from "../../../aviculture/services/aviculture-get-wage-type";
import { ProvinceFreeSalesTransactions } from "../province-free-sales-transactions/ProvinceFreeSalesTransactions";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { provinceGetFreeSalesDashboardService } from "../../services/province-get-free-sales-dashboard";

export const ProvinceFreeSales = () => {
  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 [value, setValue] = useState(0);
  const [dashboardData, setDashboardData] = useState([]);
  const [wageType, setWageType] = useState();

  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

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

  const handleChange = (event, newValue) => {
    setValue(newValue);
    refreshDashboard();
  };

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `out-province-poultry-requests/?search=filter&value=${textValue}&page=${page}&role=${getRoleFromUrl()}&page_size=${perPage}&date1=${selectedDate1}&date2=${selectedDate2}&state=pending`
    );
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const refreshDashboard = () => {
    dispatch(
      provinceGetFreeSalesDashboardService({
        selectedDate1,
        selectedDate2,
        textValue,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

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

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

  useEffect(() => {
    fetchApiData(1);
    refreshDashboard();

    dispatch(avicultureGetWageType()).then((r) => {
      setWageType(r.payload.data.status);
    });
  }, [dispatch, perPage]);

  useEffect(() => {
    if (value === 0) {
      fetchApiData(1);
    }
    refreshDashboard();
  }, [selectedDate1, selectedDate2, value]);

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        <ProvinceFreeSalesOperations
          key={i}
          item={item}
          wageType={wageType}
          fetchApiData={fetchApiData}
        />,
        <Chip
          key={i}
          label={item.outState}
          color={
            item.outState === "در انتظار پرداخت"
              ? "info"
              : item.outState === "در انتظار تایید"
              ? "warning"
              : item.outState === "رد شده"
              ? "error"
              : "success"
          }
          size="small"
          variant="outlined"
        />,
        `${item?.registrar?.fullname}`,
        item.orderCode,
        item.buyer?.firstName
          ? `${item.buyer?.firstName} ${item.buyer?.lastName} (${item.buyer?.mobile}) / ${item.buyer.province} - ${item.buyer.city}`
          : item?.outProvincePoultryRequestBuyer.type === "killhouse"
          ? `کشتارگاه ${item.buyerFullname} (${item.buyerMobile}) / شناسه یکتا ${item.outProvincePoultryRequestBuyer?.killHouseUniqueId} / ${item.buyerProvince} - ${item.buyerCity}`
          : `کشتارکن ${item.buyerFullname} (${
              item.buyerMobile
            }) / نام کشتارگاه ${
              item.killerKillHouseUnitName ? item.killerKillHouseUnitName : "-"
            } / شناسه یکتا ${
              item.killerKillHouseUniqueId ? item.killerKillHouseUniqueId : "-"
            } / استان ${
              item.killerKillHouseProvince ? item.killerKillHouseProvince : "-"
            } / شهر ${
              item.killerKillHouseCity ? item.killerKillHouseCity : "-"
            }`,
        item?.outProvincePoultryRequestBuyer?.type === "killhouse"
          ? "محل کشتارگاه"
          : item?.killerKillHouseUnitName
          ? `کشتارگاه ${item?.killerKillHouseUnitName} / ${item?.killerKillHouseProvince} / ${item?.killerKillHouseCity}`
          : "-",
        item?.hasWage ? item?.payerFullname : "-",
        item?.paymentLink ? (
          <a
            href={item?.paymentLink}
            target="_blank"
            rel="noreferrer"
            dir="ltr"
          >
            {item?.paymentLink.length > 25
              ? `${item?.paymentLink.slice(0, 25)}...`
              : item?.paymentLink}
          </a>
        ) : (
          "-"
        ),
        `${item.poultry?.unitName} (${item.poultry.user.mobile})`,
        formatJustDate(item.createDate),
        formatJustDate(item.sendDate),
        item.hatching.age,
        item.IndexWeight?.toLocaleString(),
        item.quantity.toLocaleString(),
        Math.floor(item.IndexWeight * item.quantity)?.toLocaleString(),
        item?.freezing ? "انجماد" : "عادی",
        item?.hasWage ? "دارد" : "ندارد",
        item.hatching?.city,
        item.hatching?.province,
        item.hatching.hatchingLeftOver
          ? item.hatching.hatchingLeftOver.toLocaleString()
          : item.hatching.leftOver.toLocaleString(),
        item.hatching.hatchingQuantity?.toLocaleString(),
        item.totalWageAmount?.toLocaleString() + " ریال",
        item?.outProvinceDriverInfo?.driverhealthCode || "-",
      ];
    });

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

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

    try {
      const response = await axios.get(
        `out-province-poultry-requests/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&date1=${selectedDate1}&date2=${selectedDate2}&state=pending&role=${getRoleFromUrl()}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      refreshDashboard();
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
      dispatch(LOADING_END());
    }
  };

  return (
    <Grid container justifyContent="center">
      <Grid container justifyContent="center" alignItems="center">
        <Tabs
          value={value}
          onChange={handleChange}
          aria-label="simple tabs example"
          scrollButtons="auto"
          variant="scrollable"
          centered
          allowScrollButtonsMobile
        >
          <Tab label="درخواست های جدید" />
          <Tab label="تایید شده" />
          <Tab label="رد شده" />
          <Tab label="خریداران" />
          <Tab label="پرداختی ها" />
        </Tabs>
        <Grid pt={2} px={2}>
          <Grid container justifyContent="center" alignItems="center">
            <ResponsiveTable
              isDashboard
              noPagination
              columns={[
                "تعداد فارم",
                "تعداد فروش",
                "حجم فروش",
                "وزن فروش",
                "تعداد فروش های تایید شده بدون تعرفه",
                "حجم فروش های تایید شده بدون تعرفه",
                "وزن فروش های تایید شده بدون تعرفه",
                "تعداد فروش های تایید شده با تعرفه",
                "حجم فروش های تایید شده با تعرفه",
                "وزن فروش های تایید شده با تعرفه",
                "تعداد کل فروش های تایید شده",
                "حجم کل فروش های تایید شده",
                "وزن کل فروش های تایید شده",
              ]}
              data={[
                [
                  dashboardData?.poultries?.toLocaleString(),
                  dashboardData?.totalNumberOfPoultryRequest?.toLocaleString(),
                  dashboardData?.totalPoultryRequestQuantity?.toLocaleString(),
                  Math.round(
                    dashboardData?.totalPoultryRequestWeight
                  )?.toLocaleString(),
                  dashboardData?.totalNumberOfAcceptedPoultryRequestWithOutWage?.toLocaleString(),
                  dashboardData?.totalAcceptedPoultryRequestQuantityWithOutWage?.toLocaleString(),
                  Math.round(
                    dashboardData?.totalAcceptedPoultryRequestWeightWithOutWage
                  )?.toLocaleString(),
                  dashboardData?.totalNumberOfAcceptedPoultryRequestWithWage?.toLocaleString(),
                  dashboardData?.totalAcceptedPoultryRequestQuantityWithWage?.toLocaleString(),
                  Math.round(
                    dashboardData?.totalAcceptedPoultryRequestWeightWithWage
                  )?.toLocaleString(),
                  dashboardData?.totalNumberOfAcceptedPoultryRequest?.toLocaleString(),
                  dashboardData?.totalAcceptedPoultryRequestQuantity?.toLocaleString(),
                  dashboardData?.totalAcceptedPoultryRequestWeight?.toLocaleString(),
                ],
              ]}
              title="خلاصه اطلاعات"
            />
          </Grid>

          {value === 0 && (
            <Grid
              container
              alignItems="start"
              direction="column"
              gap={2}
              xs={12}
            >
              <Grid
                container
                alignItems="center"
                gap={SPACING.SMALL}
                mt={SPACING.SMALL}
              >
                <Grid style={{ width: 190 }}>
                  <Button
                    className="avicultureNewRequestBtn"
                    variant={"contained"}
                    fullWidth
                    onClick={() => {
                      dispatch(
                        DRAWER({
                          right: !(window.innerWidth <= 600),
                          bottom: window.innerWidth <= 600,
                          title: "ثبت درخواست فروش به خارج استان",
                          size: {
                            xs: "100%",
                            md: "400px",
                          },
                          content: (
                            <ProvinceFreeSaleNewRequest
                              fetchApiData={fetchApiData}
                            />
                          ),
                        })
                      );
                    }}
                  >
                    فروش به خارج استان
                  </Button>
                </Grid>
              </Grid>
              <Grid
                container
                gap={2}
                xs={12}
                justifyContent="space-between"
                mt={2}
              >
                <Grid container gap={2}>
                  <Grid>
                    <DatePicker
                      label="از تاریخ"
                      id="date"
                      renderInput={(params) => (
                        <TextField style={{ width: "160px" }} {...params} />
                      )}
                      value={selectedDate1}
                      onChange={(e) => {
                        setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                      }}
                    />
                  </Grid>
                  <Grid>
                    <DatePicker
                      label="تا تاریخ"
                      id="date"
                      renderInput={(params) => (
                        <TextField style={{ width: "160px" }} {...params} />
                      )}
                      value={selectedDate2}
                      onChange={(e) => {
                        setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                      }}
                    />
                  </Grid>
                  <form onSubmit={handleSubmit}>
                    <TextField
                      id="outlined-basic"
                      size="small"
                      autoComplete="off"
                      label="جستجو"
                      variant="outlined"
                      style={{ width: 250 }}
                      onChange={handleTextChange}
                    />
                    <Button
                      type="submit"
                      onClick={handleSubmit}
                      endIcon={<RiSearchLine />}
                    >
                      جستجو
                    </Button>
                  </form>
                  <Grid>
                    <Tooltip title="خروجی اکسل کلی">
                      <a
                        href={`${
                          axios.defaults.baseURL
                        }general_free_bar_excel/?date1=${selectedDate1}&date2=${selectedDate2}&role=${getRoleFromUrl()}&key=${userKey}&search=filter&value=${textValue}`}
                        rel="noreferrer"
                      >
                        <Button color="primary">
                          <RiFileExcel2Fill size={32} />
                        </Button>
                      </a>
                    </Tooltip>
                  </Grid>
                  <Grid>
                    <Tooltip title="خروجی اکسل درخواست های جدید">
                      <a
                        href={`${
                          axios.defaults.baseURL
                        }bar_free_excel/?date1=${selectedDate1}&date2=${selectedDate2}&state=pending&role=${getRoleFromUrl()}&key=${userKey}`}
                        rel="noreferrer"
                      >
                        <Button color="success">
                          <RiFileExcel2Fill size={32} />
                        </Button>
                      </a>
                    </Tooltip>
                  </Grid>
                </Grid>
                {getRoleFromUrl() !== "CityOperator" && (
                  <Grid>
                    <Button
                      color="error"
                      variant={"contained"}
                      onClick={() => {
                        dispatch(provinceApproveFreeSaleService()).then((r) => {
                          if (r.payload.error) {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: r.payload.error,
                              severity: "error",
                            });
                          } else {
                            fetchApiData(1);
                            refreshDashboard();
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "عملیات با موفقیت انجام شد.",
                              severity: "success",
                            });
                          }
                        });
                      }}
                    >
                      تایید یکجا
                    </Button>
                  </Grid>
                )}
              </Grid>
              <Grid container gap={2} xs={12} justifyContent="center">
                <ResponsiveTable
                  data={tableData}
                  columns={[
                    "ردیف",
                    "عملیات",
                    "وضعیت",
                    "ثبت کننده سفارش",
                    "کد سفارش",
                    "اطلاعات خریدار",
                    "محل کشتار",
                    "پرداخت کننده",
                    "لینک پرداخت",
                    "مرغدار",
                    "تاریخ ثبت درخواست",
                    "تاریخ کشتار",
                    "سن مرغ",
                    "میانگین وزن (کیلوگرم)",
                    "تعداد",
                    "وزن کل (کیلوگرم)",
                    "نوع کشتار",
                    "تعرفه",
                    "شهر",
                    "استان",
                    "مانده در سالن",
                    "جوجه ریزی اولیه",
                    "مبلغ تراکنش (ریال)",
                    "کد بهداشتی ماشین",
                  ]}
                  handlePageChange={handlePageChange}
                  totalRows={totalRows}
                  page={page}
                  perPage={perPage}
                  handlePerRowsChange={handlePerRowsChange}
                  title="فروش خارج از استان"
                />
              </Grid>
            </Grid>
          )}
          {value === 1 && (
            <ProvinceFreeSalesAcceptedRequests state="accepted" />
          )}
          {value === 2 && (
            <ProvinceFreeSalesAcceptedRequests state="rejected" />
          )}
          {value === 3 && <ProvinceFreeSalsesManageBuyers />}
          {value === 4 && <ProvinceFreeSalesTransactions />}
        </Grid>
      </Grid>
    </Grid>
  );
};
