import React, { useContext, useEffect, useState } from "react";
import { Button, Chip, TextField, Tooltip } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch } from "react-redux";
import axios from "axios";
import { RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import { RiFileExcel2Fill } from "react-icons/ri";
import { useSelector } from "react-redux";

import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ProvinceFreeSalesAcceptedRequestsOperations } from "../province-free-sales-accepted-requests-operations/ProvinceFreeSalesAcceptedRequestsOperations";
import { formatJustDate } from "../../../../utils/formatTime";
import { VetFarmSubmitClearanceCode } from "../../../vet-farm/components/vet-farm-submit-clearance-code/VetFarmSubmitClearanceCode";

export const ProvinceFreeSalesAcceptedRequests = ({ state }) => {
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [accepttableData, setaccepteTableData] = useState([]);
  const [columnsRejected, setcolumnsRejected] = useState([]);

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  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=${state}`
    );

    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };
  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 handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };
  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };
  //   const updateTable = () => {
  //     fetchApiData(page !== 0 ? page : 1);
  //   };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        getRoleFromUrl() === "CityOperator" ? (
          "-"
        ) : (
          <ProvinceFreeSalesAcceptedRequestsOperations
            item={item}
            fetchApiData={fetchApiData}
          />
        ),
        <Chip
          key={i}
          label={item.outState}
          color={
            item.outState === "تایید شده"
              ? "success"
              : item.outState === "رد شده"
              ? "error"
              : "info"
          }
          size="small"
          variant="outlined"
        />,
        `${item?.totalWageAmount?.toLocaleString()} ریال`,
        `${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.poultry?.unitName} (${item.poultry.user.mobile})`,
        <Tooltip placement="left-start" key={i}>
          <Button
            variant="contained"
            color="primary"
            size="small"
            sx={{ minWidth: 0, px: 1.5, py: 0.25, fontSize: "0.8rem" }}
            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"
              ? "ثبت"
              : "مشاهده"}
          </Button>
        </Tooltip>,
        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.leftOver?.toLocaleString(),
        item.hatching.hatchingQuantity?.toLocaleString(),
        item?.outProvinceDriverInfo?.driverCar
          ? item?.outProvinceDriverInfo?.driverCar
          : "-",
        item?.outProvinceDriverInfo?.driverPelak
          ? item?.outProvinceDriverInfo?.driverPelak
          : "-",
        item?.outProvinceDriverInfo?.driverName
          ? item?.outProvinceDriverInfo?.driverName
          : "-",
        item?.outProvinceDriverInfo?.driverMobile
          ? item?.outProvinceDriverInfo?.driverMobile
          : "-",
        item?.outProvinceDriverInfo?.driverhealthCode
          ? item?.outProvinceDriverInfo?.driverhealthCode
          : "-",
        // getBuyerType(item),
        item?.outProvinceDriverInfo?.driverhealthCode,
      ];
    });
    setaccepteTableData(d);

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

        <Chip
          key={i}
          label={item.outState}
          color={
            item.outState === "تایید شده"
              ? "success"
              : item.outState === "رد شده"
              ? "error"
              : "info"
          }
          size="small"
          variant="outlined"
        />,
        `${item?.totalWageAmount?.toLocaleString()} ریال`,
        item.outProvinceRequestCanceller?.fullname
          ? `${item.outProvinceRequestCanceller?.fullname} (${item.outProvinceRequestCanceller?.mobile})`
          : item.agent?.fullname
          ? `${item.agent?.fullname} (${item.agent?.mobile})`
          : "-",
        `${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.poultry?.unitName} (${item.poultry.user.mobile})`,
        item.quarantineCode ? item?.quarantineCode : "-",
        formatJustDate(item?.createDate),
        formatJustDate(item.sendDate),
        item.IndexWeight?.toLocaleString(),
        item.hatching.age,
        item.quantity.toLocaleString(),
        Math.floor(item.IndexWeight * item.quantity)?.toLocaleString(),
        item?.freezing ? "انجماد" : "عادی",
        item?.hasWage ? "دارد" : "ندارد",
        item.hatching?.city,
        item.hatching?.province,
        item.hatching.leftOver?.toLocaleString(),
        item.hatching.hatchingQuantity?.toLocaleString(),
        item?.outProvinceDriverInfo?.driverCar
          ? item?.outProvinceDriverInfo?.driverCar
          : "-",
        item?.outProvinceDriverInfo?.driverPelak
          ? item?.outProvinceDriverInfo?.driverPelak
          : "-",
        item?.outProvinceDriverInfo?.driverName
          ? item?.outProvinceDriverInfo?.driverName
          : "-",
        item?.outProvinceDriverInfo?.driverMobile
          ? item?.outProvinceDriverInfo?.driverMobile
          : "-",
        item?.outProvinceDriverInfo?.driverhealthCode
          ? item?.outProvinceDriverInfo?.driverhealthCode
          : "-",
      ];
    });

    setcolumnsRejected(r);
  }, [data]);

  // useEffect(() => {
  //   const d = data?.map((item, i) => {
  //     return [
  //       page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
  //       item?.poultryRequest?.freezing ? "انجماد" : "عادی",
  //     ];
  //   });

  //   setaccepteTableData(d);
  // }, [data]);

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

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

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

      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}
      mt={4}
    >
      <Grid container gap={2} xs={12}>
        <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=${state}&role=${getRoleFromUrl()}&key=${userKey}`}
              rel="noreferrer"
            >
              <Button color="success">
                <RiFileExcel2Fill size={32} />
              </Button>
            </a>
          </Tooltip>
        </Grid>
      </Grid>
      {/* <Grid container gap={2} xs={12} justifyContent="center">
        <ResponsiveTable
          data={state ? accepttableData : tableDataRejected}
          columns={
            state
              ? [
                  "ردیف",
                  "عملیات",
                  "وضعیت",
                  "تاریخ سفارش",
                  "نوع فروش",
                  "ثبت کننده سفارش",
                  "خریدار",
                  "مرغداری",
                  "شرکت زنجیره",
                  "کد بهداشتی",
                  "کد قرنطینه",
                  "راننده",
                  "نوع خودرو",
                  "پلاک",
                  "حجم",
                  "میانگین وزن",
                  "وزن",
                ]
              : [
                  "ردیف",
                  "وضعیت",
                  "حذف/رد کننده",
                  "تاریخ سفارش",
                  "نوع فروش",
                  "خریدار",
                  "مرغداری",
                  "شرکت زنجیره",
                  "کد بهداشتی",
                  "کد قرنطینه",
                  "راننده",
                  "نوع خودرو",
                  "پلاک",
                  "حجم",
                  "میانگین وزن",
                  "وزن",
                ]
          }
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title={state === 0 ? " تایید شده" : " رد شده"}
        />
      </Grid> */}

      <Grid container gap={2} xs={12} justifyContent="center">
        <ResponsiveTable
          data={state === "accepted" ? accepttableData : columnsRejected}
          columns={
            state === "accepted"
              ? [
                  "ردیف",
                  "عملیات",
                  "وضعیت",
                  "مبلغ کل ",
                  "ثبت کننده سفارش",
                  "کد سفارش",
                  "اطلاعات خریدار",
                  "محل کشتار",
                  "پرداخت کننده",
                  "مرغدار",
                  "کد قرنطینه",
                  "تاریخ ثبت درخواست",
                  "تاریخ کشتار",
                  "سن مرغ",
                  "میانگین وزن (کیلوگرم)",
                  "تعداد",
                  "وزن کل (کیلوگرم)",
                  "نوع کشتار",
                  "تعرفه",
                  "شهر",
                  "استان",
                  "مانده در سالن",
                  "جوجه ریزی اولیه",
                  "نوع خودرو",
                  "پلاک",
                  "نام راننده",
                  "تلفن راننده",
                  "کد بهداشتی ماشین",
                ]
              : [
                  "ردیف",
                  "وضعیت",
                  "مبلغ کل",
                  "رد/لغو کننده",
                  "ثبت کننده سفارش",
                  "کد سفارش",
                  "اطلاعات خریدار",
                  "محل کشتار",
                  "پرداخت کننده",
                  "مرغدار",
                  "کد قرنطینه",
                  "تاریخ ثبت درخواست",
                  "تاریخ کشتار",
                  "میانگین وزن (کیلوگرم)",
                  "سن مرغ",
                  "تعداد",
                  "وزن کل (کیلوگرم)",
                  "نوع کشتار",
                  "تعرفه",
                  "شهر",
                  "استان",
                  "مانده در سالن",
                  "جوجه ریزی اولیه",
                  "نوع خودرو",
                  "پلاک",
                  "نام راننده",
                  "تلفن راننده",
                  "کد بهداشتی ماشین",
                ]
          }
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title={state === "accepted" ? " تایید شده" : " رد شده"}
        />
      </Grid>
    </Grid>
  );
};
