import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { VetFarmSubmitClearanceCode } from "../vet-farm-submit-clearance-code/VetFarmSubmitClearanceCode";
import { VetFarmEditOutOfProvinceTrafficCode } from "../vet-farm-edit-out-out-province-traffic-code/VetFarmEditOutOfProvinceTrafficCode";
import { Grid } from "../../../../components/grid/Grid";
import { vetFarmOutProvinceGetDashboard } from "../../services/vet-farm-out-province-get-dashboard";
import { formatJustDate } from "../../../../utils/formatTime";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import VisibilityIcon from "@mui/icons-material/Visibility";

export const VetFarmOutOfProvince = ({ readOnly }) => {
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [dashboardData, setDashboardData] = useState([]);
  const [dataTableM, setDataTableM] = useState([]);

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

  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  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 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=accepted`
    );

    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);
    dispatch(
      vetFarmOutProvinceGetDashboard({
        selectedDate1,
        selectedDate2,
        text: textValue,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  }, [dispatch, selectedDate1, selectedDate2, perPage]);

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

    try {
      const response = await axios.get(
        `out-province-poultry-requests/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&state=accepted&role=${getRoleFromUrl()}`
      );

      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,

        <Typography variant="body2" style={{ color: "green" }} key={i}>
          {item.outState}
        </Typography>,
        `${item?.registrar?.fullname}`,
        item.orderCode,
        item.buyer?.firstName
          ? `${item.buyer?.firstName} ${item.buyer?.lastName} (${item.buyer?.mobile}) / ${item.buyer.province} - ${item.buyer.city}`
          : `${item.buyerFullname} (${item.buyerMobile}) / ${item.buyerProvince} - ${item.buyerCity}`,
        item?.hasWage ? item?.payerFullname : "-",
        `${item.poultry?.unitName} (${item.poultry.user.mobile})`,
        item?.poultry?.age,
        item?.IndexWeight?.toLocaleString(),
        // item?.killer
        //   ? `${item?.killer?.name} (${item?.killer?.killHouseOperator?.user?.mobile})`
        //   : "-",
        item.quantity.toLocaleString(),
        Math.floor(item.IndexWeight * item.quantity)?.toLocaleString(),
        <Tooltip
          key={i}
          placement="top"
          title={
            getRoleFromUrl() === "VetFarm" || getRoleFromUrl() === "AdminX"
              ? "ثبت کد قرنطینه"
              : "مشاهده کد قرنطینه"
          }
        >
          <IconButton
            color="primary"
            size="small"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "ثبت کد قرنطینه",
                  size: {
                    xs: "340px",
                    md: "690px",
                  },
                  content: (
                    <VetFarmSubmitClearanceCode
                      key={i}
                      readOnly={getRoleFromUrl() === "CityOperator"}
                      item={item}
                      updateTable={updateTable}
                    />
                  ),
                })
              );
            }}
          >
            {getRoleFromUrl() === "VetFarm" || getRoleFromUrl() === "AdminX" ? (
              <AddCircleOutlineIcon fontSize="small" />
            ) : (
              <VisibilityIcon fontSize="small" />
            )}
          </IconButton>
        </Tooltip>,

        item?.totalSystemQuarantineQuantity?.toLocaleString() || "-",
        readOnly ? (
          item?.outProvinceDriverInfo?.driverhealthCode
        ) : (
          <VetFarmEditOutOfProvinceTrafficCode
            key={i}
            item={item}
            trafficCode={item?.outProvinceDriverInfo?.driverhealthCode}
          />
        ),

        item?.outProvinceDriverInfo?.driverCar || "-",
        item?.outProvinceDriverInfo?.driverPelak
          ? item?.outProvinceDriverInfo?.driverPelak
          : "-",
        item?.outProvinceDriverInfo?.driverName
          ? item?.outProvinceDriverInfo?.driverName
          : "",
        item?.outProvinceDriverInfo?.driverMobile
          ? item?.outProvinceDriverInfo?.driverMobile
          : "",
        formatJustDate(item?.createDate),
        formatJustDate(item?.sendDate),
        item?.totalWageAmount || "-",
        item?.hatching?.city,
        item?.hatching?.province,
        item?.hatching?.leftOver?.toLocaleString(),
        item?.hatching?.hatchingQuantity?.toLocaleString(),
      ];
    });

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

  const tableTitle = (
    <Grid container gap={2} xs={12} alignItems="center">
      <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
          // disabled={!textValue}
          type="submit"
          onClick={handleSubmit}
          endIcon={<RiSearchLine />}
        >
          جستجو
        </Button>
      </form>
      <Grid>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${
              axios.defaults.baseURL
            }bar_free_excel/?date1=${selectedDate1}&date2=${selectedDate2}&state=accepted&role=${getRoleFromUrl()}&key=${userKey}&search=filter&value=${textValue}`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>
    </Grid>
  );

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        {tableTitle}
        <Grid container mt={2} mb={4} isDashboard xs={12}>
          <ResponsiveTable
            noPagination
            isDashboard
            columns={[
              "تعداد بار",
              "مجموع حجم",
              "مجموع وزن",
              "میانگین وزنی",
              "تعداد بار های دارای کد قرنطینه",
              "تعدا بار فاقد کد قرنطینه",
              "مجموع جوجه ریزی",
              "مجموع مانده در سالن",
            ]}
            data={[
              [
                dashboardData?.lenBar?.toLocaleString(),
                dashboardData?.quantity?.toLocaleString(),
                dashboardData?.weight?.toLocaleString(),
                dashboardData?.indexWeight?.toLocaleString(),
                dashboardData?.hasCode?.toLocaleString(),
                dashboardData?.hasntCode?.toLocaleString(),
                dashboardData?.hatchingQuantity?.toLocaleString(),
                dashboardData?.leftOver?.toLocaleString(),
              ],
            ]}
            title={"خلاصه اطلاعات"}
          />
        </Grid>
        <ResponsiveTable
          data={dataTableM}
          columns={[
            "ردیف",
            "وضعیت",
            "ثبت کننده سفارش",
            "کد سفارش",
            "اطلاعات خریدار",
            "پرداخت کننده",
            "مرغدار",
            "سن مرغ",
            "میانگین وزن (کیلوگرم)",
            "تعداد",
            "وزن کل (کیلوگرم)",
            "ثبت کد قرنطینه",
            "تعداد در قرنطینه",
            "کد بهداشتی ماشین",
            "نوع خودرو",
            "پلاک",
            "نام راننده",
            "تلفن راننده",
            "تاریخ ثبت درخواست",
            "تاریخ کشتار",
            "تعرفه",
            "شهر",
            "استان",
            "مانده در سالن",
            "جوجه ریزی اولیه",
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title="درخواست های فروش به خارج استان"
        />
      </Grid>
    </Grid>
  );
};
