import { Grid } from "../../../../components/grid/Grid";
import React, { useContext, useEffect, useState } from "react";
import {
  Autocomplete,
  Button,
  Checkbox,
  IconButton,
  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 { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { CheckCleanceCode } from "../../../../components/check-clearance-code/ChechClearanceCode";
import { provinceNationalTransportManagementInfoDashboardService } from "../../../province/services/province-national-transport-managemant-info-dashboard-service";
import { useParams } from "react-router-dom";
import { getSamasatProvinces } from "../../../../utils/getSamasatProvinces";
import { formatJustDate } from "../../../../utils/formatTime";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";

export const NationalInfoTransports = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [selectedProvince, setSelectedProvince] = useState("");

  const getProvince = () => {
    if (key === undefined) {
      return selectedProvince === "همه" ? "" : selectedProvince;
    } else {
      return key;
    }
  };

  const getDashboardData = () => {
    dispatch(
      provinceNationalTransportManagementInfoDashboardService({
        date1: withDate ? selectedDate1 : null,
        date2: withDate ? selectedDate2 : null,
        search: textValue,
        province: getProvince(),
        PartIdCode: unitkey !== undefined ? unitkey : null,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  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 [withDate, setWithDate] = useState(true);
  const [dashboardData, setDashboardData] = useState([]);
  const { key, unitkey, name } = useParams();

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `https://rsibackend.rasadyar.com/app/transporting-detail/?search=${textValue}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }&page=${page}&page_size=${perPage}${
        unitkey !== undefined ? "&PartIdCode=" + unitkey : ""
      }&province=${getProvince()}`
    );
    dispatch(LOADING_END());
    getDashboardData();
    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(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        <CheckCleanceCode key={i} clearanceCode={item?.TrackingCode} />,
        formatJustDate(item?.Date),
        item?.DesUnitName,
        item?.DesPartIdCode,
        item?.Province,
        item?.City,
        item?.GoodAmount?.toLocaleString(),
        item?.TrackingStatusDescription,
        item?.Out ? "خارج استان" : "داخل استان",
        item?.SourceUnitName,
        item?.hatching?.poultry?.PartIdCode,
        item?.hatching?.RequestCode,
        item?.hatching?.poultry?.Province,
        item?.hatching?.poultry?.City,
        item?.Age,
        item?.hatching?.PedigreeName,
        // <Button
        //   key={i}
        //   variant="contained"
        //   size="small"
        //   color="primary"
        //   onClick={() => {
        //     dispatch(
        //       DRAWER({
        //         top: true,
        //         content: <NationalInfoDetails data={item} size={1000} />,
        //         title: "گزارش حمل مرغ زنده",
        //       })
        //     );
        //   }}
        // >
        //   مشاهده
        // </Button>,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `https://rsibackend.rasadyar.com/app/transporting-detail/?search=${textValue}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }&page=${1}&page_size=${perPage}${
          unitkey !== undefined ? "&PartIdCode=" + unitkey : ""
        }&province=${getProvince()}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  const getProvinceList = () => {
    return [{ name: "همه" }, ...getSamasatProvinces()];
  };

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      gap={2}
      mt={4}
    >
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        {key === undefined && unitkey === undefined && name === undefined && (
          <Grid minWidth={210}>
            <Autocomplete
              size="small"
              disablePortal
              id="hatching"
              options={getProvinceList().map((i) => {
                return {
                  label: i.name,
                };
              })}
              onChange={(event, value) => {
                if (value.label !== "همه") {
                  setSelectedProvince(value.label);
                } else {
                  setSelectedProvince("");
                }
              }}
              renderInput={(params) => (
                <TextField {...params} label="انتخاب استان" />
              )}
            />
          </Grid>
        )}

        <Grid
          container
          gap={1}
          style={{
            borderStyle: "solid",
            borderWidth: "1px",
            padding: "5px",
            borderRadius: "15px",
            borderColor: "gray",
            justifyContent: "left",
          }}
          alignItems="center"
        >
          <Checkbox
            icon={<ToggleOffOutlinedIcon />}
            checkedIcon={<ToggleOnIcon />}
            checked={withDate}
            onChange={() => setWithDate(!withDate)}
            color="primary"
            size="large"
          />
          <Grid>
            <DatePicker
              disabled={!withDate}
              label="از تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  sx={{ width: { xs: "126px", md: "160px" } }}
                  {...params}
                />
              )}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              disabled={!withDate}
              label="تا تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  sx={{ width: { xs: "126px", md: "160px" } }}
                  {...params}
                />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        </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>
          <Tooltip
            placement="right"
            title={
              withDate
                ? "دانلود اکسل"
                : "برای دانلود اکسل، بازه تاریخی را فعال کنید"
            }
          >
            <IconButton
              size="small"
              color="success"
              component="a"
              href={`https://rsibackend.rasadyar.com/app/all_send_different_bar_excel/?search=${textValue}${
                withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
              }&province=${getProvince()}`}
              disabled={!withDate}
            >
              <RiFileExcel2Fill size={36} style={{ cursor: "pointer" }} />
            </IconButton>
          </Tooltip>
        </Grid>
      </Grid>

      <Grid container mt={2} mb={4} isDashboard xs={12}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد بار",
            "حجم بار",
            "میانگین سن کشتار",
            "تعداد بار داخل استان",
            "حجم بار داخل استان",
            "درصد داخل استان",
            "تعداد بار خارج استان",
            "حجم بار خارج استان",
            "درصد خارج استان",
          ]}
          data={[
            [
              dashboardData?.barCount?.toLocaleString(),
              dashboardData?.barQuantity?.toLocaleString(),
              Math.floor(dashboardData?.totalBarKillingAge),
              dashboardData?.inputBarCount?.toLocaleString(),
              dashboardData?.inputBarQuantity?.toLocaleString(),
              dashboardData?.inputBarPercent?.toFixed(1),
              dashboardData?.outputBar?.toLocaleString(),
              dashboardData?.outputBarQuantity?.toLocaleString(),
              dashboardData?.outputBarPercent?.toFixed(1),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>
      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "کد رهگیری قرنطینه",
          "تاریخ کشتار",
          "نام کشتارگاه",
          "شناسه یکتا کشتار گاه",
          "استان کشتارگاه",
          "شهر کشتارگاه",
          "تعداد ",
          "وضعیت ",
          "مقصد کشتار",
          "نام مرغدار",
          "شناسه یکتا مرغداری",
          "شناسه جوجه ریزی",
          "استان مرغدار",
          "شهرستان مرغدار",
          "سن کشتار",
          "نژاد",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={
          key || name
            ? `گزارش  اطلاعات بار ${key || name} `
            : `گزارش  اطلاعات بار`
        }
      />
    </Grid>
  );
};
