import React, { useContext, useEffect, useState } from "react";
import axios from "axios";
import { useDispatch } from "react-redux";
import {
  LOADING_START,
  LOADING_END,
} from "../../../../lib/redux/slices/appSlice";
import { showSnackbar } from "../../../../utils/showSnackbar";
import { AppContext } from "../../../../contexts/AppContext";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import {
  Autocomplete,
  Checkbox,
  CircularProgress,
  Grid,
  TextField,
  IconButton,
  Tooltip,
  Button,
} from "@mui/material";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import SearchIcon from "@mui/icons-material/Search";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { formatJustDate } from "../../../../utils/formatTime";
import { CheckCleanceCode } from "../../../../components/check-clearance-code/ChechClearanceCode";
import { RiFileExcel2Fill } from "react-icons/ri";

export const TotalCargoInformation = () => {
  const [cargoInformation, setCargoInformation] = useState(null);
  const [dashboardInformation, setDashboardInformation] = useState(null);
  const [tableData, setTableData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(20);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [withDate, setWithDate] = useState(true);
  const [provinceOptions, setProvinceOptions] = useState([]);
  const [selectedProvince, setSelectedProvince] = useState("");
  const [isProvinceLoading, setIsProvinceLoading] = useState(false);
  const [productOptions, setProductOptions] = useState([]);
  const [selectedProduct, setSelectedProduct] = useState("");
  const [isProductLoading, setIsProductLoading] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const [searchInput, setSearchInput] = useState("");

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

  const columns = [
    "ردیف",
    "کد رهگیری",
    "محصول",
    "اقلام",
    "مقدار",
    "واحد",
    "تاریخ",
    "مقصد",
    "شناسه مقصد",
    "استان مقصد",
    "شهرستان مقصد",
    "مبدا",
    "شناسه مبدا",
    "استان مبدا",
    "شهرستان مبدا",
    "نوع حمل",
    "مقصد قبلی",
    "تغییر مقصد",
    "کد رهگیری خودرو",
    "تاریخ تخلیه",
    "تخلیه",
  ];

  const dashboardColumns = [
    "محصول",
    "تعداد بار",
    "حجم بار (کیلوگرم)",
    "تعداد بار داخل استان",
    "حجم بار داخل استان (کیلوگرم)",
    "درصد داخل استان",
    "تعداد بار خارج استان",
    "حجم بار خارج استان (کیلوگرم)",
    "درصد خارج استان",
    "آخرین بروزرسانی",
  ];

  const formatDateTimeFromIso = (value) => {
    if (!value) return "-";
    const dateObj = new Date(value);
    if (Number.isNaN(dateObj.getTime())) return "-";
    const date = dateObj.toLocaleDateString("fa-IR");
    const time = dateObj.toLocaleTimeString("fa-IR", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: false,
    });
    return `${date} ${time}`;
  };

  const formatNumber = (value) => {
    if (value === null || value === undefined) {
      return "-";
    }
    if (typeof value === "number") {
      return value.toLocaleString("fa-IR");
    }
    return value;
  };

  const formatPercent = (value) => {
    if (value === null || value === undefined) {
      return "-";
    }
    const numericValue = Number(value);
    if (Number.isNaN(numericValue)) {
      return "-";
    }
    return `${numericValue.toFixed(1)}%`;
  };

  const safeValue = (value) => {
    if (value === null || value === undefined || value === "") {
      return "-";
    }
    return value;
  };

  useEffect(() => {
    setPage(1);
  }, [
    selectedDate1,
    selectedDate2,
    withDate,
    selectedProvince,
    selectedProduct,
    searchValue,
  ]);

  useEffect(() => {
    let isMounted = true;

    const fetchProvinces = async () => {
      try {
        setIsProvinceLoading(true);
        const { data } = await axios.get("iran_province/");
        if (!isMounted) {
          return;
        }
        const names =
          data?.map?.((item) => item?.name).filter((name) => !!name) ?? [];
        setProvinceOptions(names);
      } catch (err) {
        console.error("Failed to fetch provinces:", err);
      } finally {
        if (isMounted) {
          setIsProvinceLoading(false);
        }
      }
    };

    fetchProvinces();

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    let isMounted = true;

    const fetchProducts = async () => {
      try {
        setIsProductLoading(true);
        const { data } = await axios.get(
          "https://rsibackend.rasadyar.com/app/all-products-transport-products"
        );
        if (!isMounted) {
          return;
        }
        const products = Array.isArray(data?.products) ? data.products : [];
        setProductOptions(products);
      } catch (err) {
        console.error("Failed to fetch product types:", err);
      } finally {
        if (isMounted) {
          setIsProductLoading(false);
        }
      }
    };

    fetchProducts();

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    let isMounted = true;

    const fetchCargoInformation = async () => {
      try {
        setError(null);
        setIsLoading(true);
        dispatch(LOADING_START());
        const cargoParams = new URLSearchParams();
        cargoParams.append("product_type", selectedProduct || "");
        if (withDate && selectedDate1) {
          cargoParams.append("date1", selectedDate1);
        }
        if (withDate && selectedDate2) {
          cargoParams.append("date2", selectedDate2);
        }
        if (selectedProvince) {
          cargoParams.append("destination_province", selectedProvince);
        }
        if (searchValue) {
          cargoParams.append("search", searchValue);
        }
        cargoParams.append("page", page.toString());
        cargoParams.append("page_size", perPage.toString());

        const dashboardParams = new URLSearchParams();
        dashboardParams.append("product_type", selectedProduct || "");
        if (withDate && selectedDate1) {
          dashboardParams.append("date1", selectedDate1);
        }
        if (withDate && selectedDate2) {
          dashboardParams.append("date2", selectedDate2);
        }
        if (selectedProvince) {
          dashboardParams.append("destination_province", selectedProvince);
        }
        if (searchValue) {
          dashboardParams.append("search", searchValue);
        }

        const [cargoResponse, dashboardResponse] = await Promise.all([
          axios.get(
            `https://rsibackend.rasadyar.com/app/all-products-transport/?${cargoParams.toString()}`
          ),
          axios.get(
            `https://rsibackend.rasadyar.com/app/all-products-transport-dashboard/?${dashboardParams.toString()}`
          ),
        ]);
        if (!isMounted) {
          return;
        }
        const cargoData = cargoResponse.data ?? { results: [] };
        const results = cargoData?.results ?? [];
        const mappedTableData = results.map((item, index) => [
          safeValue(formatNumber(index + 1 + (page - 1) * perPage)),
          <CheckCleanceCode
            key={item?.tracking || index}
            clearanceCode={item?.tracking}
          />,
          safeValue(item?.product),
          safeValue(item?.items),
          safeValue(formatNumber(item?.quantity)),
          safeValue(item?.unit),
          safeValue(formatJustDate(item?.date)),
          safeValue(item?.destination),
          safeValue(item?.jihadiDestination),
          safeValue(item?.destinationProvince),
          safeValue(item?.destinationCity),
          safeValue(item?.origin),
          safeValue(item?.jihadiOrigin),
          safeValue(item?.originProvince),
          safeValue(item?.originCity),
          safeValue(
            item?.originProvince === item?.destinationProvince
              ? "داخل استان"
              : "خارج استان"
          ),
          safeValue(item?.destinationPrev),
          safeValue(item?.destinationChanged),
          safeValue(item?.carTrackingCode),
          safeValue(formatJustDate(item?.unloadingDate)),
          safeValue(item?.unloading),
        ]);

        setCargoInformation(cargoData);
        setTableData(mappedTableData);
        setTotalRows(cargoData?.count ?? 0);
        setDashboardInformation(dashboardResponse.data);
      } catch (err) {
        console.error("Failed to fetch total cargo information:", err);
        if (!isMounted) {
          return;
        }
        setError(err);
        showSnackbar(
          "در دریافت اطلاعات بار کل کشور خطایی رخ داد، لطفا مجددا تلاش کنید.",
          "error"
        );
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
        dispatch(LOADING_END());
      }
    };

    fetchCargoInformation();
    return () => {
      isMounted = false;
    };
  }, [
    dispatch,
    page,
    perPage,
    selectedDate1,
    selectedDate2,
    selectedProvince,
    selectedProduct,
    withDate,
    searchValue,
  ]);

  const handlePageChange = (newPage) => {
    setPage(newPage);
  };

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    const normalizedSearch = searchInput.trim();
    setSearchValue(normalizedSearch);
    setSearchInput(normalizedSearch);
    setPage(1);
  };

  if (error) {
    return <div>خطا در دریافت اطلاعات بار کل کشور</div>;
  }

  if (isLoading && (!cargoInformation || !dashboardInformation)) {
    return <div>در حال بارگذاری اطلاعات ...</div>;
  }

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      gap={2}
      mt={4}
    >
      <Grid
        container
        direction="column"
        xs={12}
        justifyContent="center"
        alignItems="center"
        gap={2}
      >
        <Grid container alignItems="center" gap={2}>
          <Grid
            container
            gap={1}
            style={{
              borderStyle: "solid",
              borderWidth: "1px",
              padding: "5px",
              borderRadius: "15px",
              borderColor: "gray",
              justifyContent: "left",
              maxWidth: "fit-content",
            }}
            alignItems="center"
            justifyContent="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) => {
                  if (!e) return;
                  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) => {
                  if (!e) return;
                  setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
          </Grid>
          <Grid
            container
            alignItems="center"
            justifyContent="center"
            gap={1}
            sx={{ maxWidth: "fit-content" }}
          >
            <Autocomplete
              options={provinceOptions}
              loading={isProvinceLoading}
              value={selectedProvince || null}
              onChange={(_, value) => {
                setSelectedProvince(value || "");
              }}
              noOptionsText="استانی یافت نشد"
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="استان مقصد"
                  size="small"
                  sx={{ width: { xs: 200, md: 240 } }}
                  InputProps={{
                    ...params.InputProps,
                    endAdornment: (
                      <>
                        {isProvinceLoading ? (
                          <CircularProgress color="inherit" size={16} />
                        ) : null}
                        {params.InputProps.endAdornment}
                      </>
                    ),
                  }}
                />
              )}
              clearOnEscape
            />

            <Autocomplete
              options={productOptions}
              loading={isProductLoading}
              value={selectedProduct || null}
              onChange={(_, value) => {
                setSelectedProduct(value || "");
              }}
              noOptionsText="محصولی یافت نشد"
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="نوع محصول"
                  size="small"
                  sx={{ width: { xs: 200, md: 240 } }}
                  InputProps={{
                    ...params.InputProps,
                    endAdornment: (
                      <>
                        {isProductLoading ? (
                          <CircularProgress color="inherit" size={16} />
                        ) : null}
                        {params.InputProps.endAdornment}
                      </>
                    ),
                  }}
                />
              )}
              clearOnEscape
            />

            <Grid
              item
              component="form"
              onSubmit={handleSubmit}
              sx={{ width: { xs: 220, md: 260 }, display: "flex" }}
            >
              <TextField
                value={searchInput}
                onChange={(event) => setSearchInput(event.target.value)}
                label="جستجو"
                size="small"
                variant="outlined"
                sx={{ flexGrow: 1 }}
              />
              <IconButton
                type="submit"
                color="primary"
                aria-label="جستجو"
                sx={{ ml: 1 }}
              >
                <SearchIcon />
              </IconButton>
              <Tooltip title="خروجی اکسل">
                <a
                  href={`https://rsibackend.rasadyar.com/app/all_products_transport_excel/?${
                    selectedProduct
                      ? "product_type=" + selectedProduct + "&"
                      : ""
                  }${selectedDate1 ? "date1=" + selectedDate1 + "&" : ""}${
                    selectedDate2 ? "date2=" + selectedDate2 + "&" : ""
                  }${
                    selectedProvince
                      ? "destination_province=" + selectedProvince
                      : ""
                  }`}
                  rel="noreferrer"
                >
                  <Button color="success">
                    <RiFileExcel2Fill size={32} />
                  </Button>
                </a>
              </Tooltip>
            </Grid>
          </Grid>
        </Grid>

        {dashboardInformation && (
          <Grid container mt={2} mb={4} isDashboard xs={12}>
            <ResponsiveTable
              noPagination
              isDashboard
              columns={dashboardColumns}
              data={[
                [
                  safeValue(dashboardInformation?.product),
                  safeValue(formatNumber(dashboardInformation?.bars)),
                  safeValue(formatNumber(dashboardInformation?.totalBarsWight)),
                  safeValue(formatNumber(dashboardInformation?.inputBars)),
                  safeValue(
                    formatNumber(dashboardInformation?.totalInputBarsWight)
                  ),
                  formatPercent(dashboardInformation?.totalInputBarsPercent),
                  safeValue(formatNumber(dashboardInformation?.outputBars)),
                  safeValue(
                    formatNumber(dashboardInformation?.totalOutputBarsWight)
                  ),
                  formatPercent(dashboardInformation?.totalOutputBarsPercent),
                  formatDateTimeFromIso(dashboardInformation?.lastUpdate),
                ],
              ]}
              title="خلاصه اطلاعات بار"
            />
          </Grid>
        )}
        <ResponsiveTable
          columns={columns}
          data={tableData}
          title="اطلاعات بار کل کشور"
          paginated={false}
          handlePageChange={handlePageChange}
          handlePerRowsChange={handlePerRowsChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
        />
      </Grid>
    </Grid>
  );
};
