import React, { useContext, useEffect, useState } from "react";
import { Button, TextField, Tooltip, Typography } 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 { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { PageTable } from "../../../../components/page-table/PageTable";
import { VetFarmSubmitClearanceCode } from "../vet-farm-submit-clearance-code/VetFarmSubmitClearanceCode";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { VetFarmEditOutOfProvinceTrafficCode } from "../vet-farm-edit-out-out-province-traffic-code/VetFarmEditOutOfProvinceTrafficCode";
import { formatJustDate } from "../../../../utils/formatTime";
import { AppContext } from "../../../../contexts/AppContext";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { vetFarmOutProvinceGetDashboard } from "../../services/vet-farm-out-province-get-dashboard";

export const ParentCompanyOutOfProvince = ({ readOnly, province }) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

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

  const handlePageChange = (page) => {
    fetchApiData(page, textValue);
  };

  const handlePerRowsChange = async (newPerPage, page) => {
    setLoading(true);
    const response = await axios.get(
      `${province}parent-company-out-province-poultry-requests/?search=filter&value=${textValue}&page=${page}&role=${getRoleFromUrl()}&page_size=${newPerPage}&date1=${selectedDate1}&date2=${selectedDate2}&state=accepted`
    );

    setData(response.data.results);
    setTotalRows(response.data.count);
    setPerPage(newPerPage);

    setLoading(false);
  };

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    setLoading(true);

    try {
      const response = await axios.get(
        `${province}parent-company-out-province-poultry-requests/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&state=accepted&role=${getRoleFromUrl()}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

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

  //   const getBuyerType = (item) => {
  //     let buyerType = "-";
  //     if (item.buyer.buyerType === "freezing") {
  //       buyerType = "انجماد";
  //     } else if (item.buyer.buyerType === "killer") {
  //       buyerType = "کشتارکن";
  //     } else if (item.buyer.buyerType === "killhouse") {
  //       buyerType = "کشتارگاه";
  //     }

  //     return buyerType;
  //   };

  const columns = [
    {
      name: "ردیف",
      selector: (item, i) => i + 1,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "60px",
    },
    {
      name: "وضعیت",
      selector: (item) => (
        <Typography variant="body2" style={{ color: "green" }}>
          {item.outState}
        </Typography>
      ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "ثبت کننده سفارش",
      selector: (item, i) => {
        return `${item?.registrar?.fullname}`;
      },
      sortable: false,
      wrap: true,
      allowOverflow: true,
      center: true,
    },
    {
      name: "کد سفارش",
      selector: (item) => item.orderCode,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "اطلاعات خریدار",
      selector: (item) =>
        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}`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "پرداخت کننده",
      selector: (item) => (item?.hasWage ? item?.payerFullname : "-"),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "مرغدار",
      selector: (item) =>
        `${item.poultry?.unitName} (${item.poultry.user.mobile})`,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "میانگین وزن (کیلوگرم)",
      selector: (item) => item.IndexWeight?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "تعداد",
      selector: (item) => item.quantity.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "وزن کل (کیلوگرم)",
      selector: (item) =>
        Math.floor(item.IndexWeight * item.quantity)?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "ثبت کد قرنطینه",
      selector: (item) => (
        <VetFarmSubmitClearanceCode
          item={item}
          readOnly={getRoleFromUrl() === "CityOperator"}
        />
      ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "140px",
    },
    {
      name: "کد بهداشتی ماشین",
      selector: (item) =>
        readOnly ? (
          item?.outProvinceDriverInfo?.driverhealthCode
        ) : (
          <VetFarmEditOutOfProvinceTrafficCode
            item={item}
            trafficCode={item?.outProvinceDriverInfo?.driverhealthCode}
          />
        ),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      width: "140px",
    },
    {
      name: "نوع خودرو",
      selector: (item) =>
        item?.outProvinceDriverInfo?.driverCar
          ? item?.outProvinceDriverInfo?.driverCar
          : "-",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "پلاک",
      selector: (item) =>
        item?.outProvinceDriverInfo?.driverPelak
          ? item?.outProvinceDriverInfo?.driverPelak
          : "-",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "نام راننده",
      selector: (item) =>
        item?.outProvinceDriverInfo?.driverName
          ? item?.outProvinceDriverInfo?.driverName
          : "-",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "تلفن راننده",
      selector: (item) =>
        item?.outProvinceDriverInfo?.driverMobile
          ? item?.outProvinceDriverInfo?.driverMobile
          : "-",
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "تاریخ ثبت درخواست",
      selector: (item) => formatJustDate(item.createDate),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "تاریخ کشتار",
      selector: (item) => formatJustDate(item.sendDate),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "سن مرغ",
      selector: (item) => item.hatching.age,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },

    {
      name: "نوع کشتار",
      selector: (item) => (item?.freezing ? "انجماد" : "عادی"),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "تعرفه",
      selector: (item) => (item?.hasWage ? "دارد" : "ندارد"),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "شهر",
      selector: (item) => item.hatching?.city,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "استان",
      selector: (item) => item.hatching?.province,
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },

    {
      name: "مانده در سالن",
      selector: (item) => item.hatching.leftOver?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },
    {
      name: "جوجه ریزی اولیه",
      selector: (item) => item.hatching.hatchingQuantity?.toLocaleString(),
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "80px",
    },

    // {
    //   name: "ماهیت خریدار",
    //   selector: (item) => getBuyerType(item),
    //   sortable: true,
    //   wrap: true,
    //   allowOverflow: true,
    //   center: true,
    //   // width: "80px",
    // },

    // {
    //   name: "عملیات",
    //   selector: (item) => item?.outProvinceDriverInfo?.driverhealthCode,
    //   sortable: true,
    //   wrap: true,
    //   allowOverflow: true,
    //   center: true,
    //   // width: "80px",
    // },
  ];

  const dispatch = useDispatch();

  const [dashboardData, setDashboardData] = useState([]);

  useEffect(() => {
    dispatch(
      vetFarmOutProvinceGetDashboard({
        selectedDate1,
        selectedDate2,
        text: textValue,
        province,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  }, [selectedDate1, selectedDate2, province]);

  return (
    <Grid
      container
      alignItems="start"
      direction="column"
      gap={2}
      xs={12}
      mt={2}
    >
      <Grid container gap={2} xs={12} alignItems="center">
        <Grid>
          <Typography variant="body1">
            درخواست های فروش خارج از استان
          </Typography>
        </Grid>
        <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={`${province}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>

      <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>

      <Grid container gap={2} xs={12} justifyContent="center">
        <PageTable
          columns={columns}
          data={data}
          progressPending={loading}
          pagination
          paginationServer
          paginationTotalRows={totalRows}
          onChangeRowsPerPage={handlePerRowsChange}
          onChangePage={handlePageChange}
        />
      </Grid>
    </Grid>
  );
};
