import { Fragment, useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useParams, useSearchParams } from "react-router-dom";
import {
  Autocomplete,
  Checkbox,
  CircularProgress,
  Tab,
  Tabs,
  TextField,
  Typography,
  IconButton,
} from "@mui/material";
import { useDispatch } from "react-redux";
import axios from "axios";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import SearchIcon from "@mui/icons-material/Search";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { formatJustDate } from "../../../../utils/formatTime";
import { CheckCleanceCode } from "../../../../components/check-clearance-code/ChechClearanceCode";
import { AppContext } from "../../../../contexts/AppContext";
import { getPoultryTransportByCodeService } from "../../services/get-poultry-transport-by-code";
import { getPoultryTransportProductsByCodeService } from "../../services/get-poultry-transport-products-by-code";
import { getPoultryTransportDashboardByCodeService } from "../../services/get-poultry-transport-dashboard-by-code";

export const PoultriesDetails = () => {
  const { key } = useParams();
  const [searchParams] = useSearchParams();
  const from = searchParams.get("from");
  const dispatch = useDispatch();
  const [tabValue, setTabValue] = useState("1");
  const [tableData, setTableData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(10);
  const [isLoading, setIsLoading] = useState(false); // eslint-disable-line no-unused-vars
  const [error, setError] = useState(null);
  const [withDate, setWithDate] = useState(true);
  const [productOptions, setProductOptions] = useState([]);
  const [selectedProduct, setSelectedProduct] = useState("");
  const [isProductLoading, setIsProductLoading] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const [searchInput, setSearchInput] = useState("");
  const [dashboardData, setDashboardData] = useState(null);
  const [provinceOptions, setProvinceOptions] = useState([]);
  const [selectedProvince, setSelectedProvince] = useState("");
  const [isProvinceLoading, setIsProvinceLoading] = useState(false);
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

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

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

  const safeValue = (value) => {
    if (value === null || value === undefined || value === "") {
      return "-";
    }
    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 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 dashboardColumns = [
    "محصول",
    "تعداد بار",
    "حجم بار (کیلوگرم)",
    "تعداد بار داخل استان",
    "حجم بار داخل استان (کیلوگرم)",
    "درصد داخل استان",
    "تعداد بار خارج استان",
    "حجم بار خارج استان (کیلوگرم)",
    "درصد خارج استان",
    "آخرین بروزرسانی",
  ];

  const handleTabChange = (event, newValue) => {
    setTabValue(newValue);
    setSelectedProduct("");
    setPage(1);
  };

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

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

  useEffect(() => {
    const isMounted = { current: true };

    const fetchProvinces = async () => {
      try {
        setIsProvinceLoading(true);
        const { data } = await axios.get("iran_province/");
        if (!isMounted.current) {
          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.current) {
          setIsProvinceLoading(false);
        }
      }
    };

    fetchProvinces();

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

  useEffect(() => {
    if (!key) return;

    const isMounted = { current: true };

    const fetchProducts = async () => {
      try {
        setIsProductLoading(true);
        const type = tabValue === "1" ? "in" : "out";
        const response = await dispatch(
          getPoultryTransportProductsByCodeService({
            code: key,
            type: type,
            date1: withDate && selectedDate1 ? selectedDate1 : "",
            date2: withDate && selectedDate2 ? selectedDate2 : "",
            search: searchValue || "",
            from: from,
          })
        );

        if (!isMounted.current) {
          return;
        }

        if (response.error) {
          console.error("Failed to fetch products:", response.error);
          return;
        }

        const products = Array.isArray(response.payload?.data?.products)
          ? response.payload.data.products
          : [];
        setProductOptions(products);
      } catch (err) {
        console.error("Failed to fetch product types:", err);
      } finally {
        if (isMounted.current) {
          setIsProductLoading(false);
        }
      }
    };

    fetchProducts();

    return () => {
      isMounted.current = false;
    };
  }, [
    key,
    tabValue,
    selectedDate1,
    selectedDate2,
    withDate,
    searchValue,
    dispatch,
  ]);

  useEffect(() => {
    if (!key) return;

    const isMounted = { current: true };

    const fetchDashboardData = async () => {
      try {
        const type = tabValue === "1" ? "in" : "out";
        const response = await dispatch(
          getPoultryTransportDashboardByCodeService({
            code: key,
            type: type,
            date1: withDate && selectedDate1 ? selectedDate1 : "",
            date2: withDate && selectedDate2 ? selectedDate2 : "",
            search: searchValue || "",
            product: selectedProduct || "",
            province: selectedProvince || "",
            from: from,
          })
        );

        if (!isMounted.current) {
          return;
        }

        if (!response.error && response.payload?.data) {
          setDashboardData(response.payload.data);
        }
      } catch (err) {
        console.error("Failed to fetch dashboard data:", err);
      }
    };

    fetchDashboardData();

    return () => {
      isMounted.current = false;
    };
  }, [
    key,
    tabValue,
    selectedDate1,
    selectedDate2,
    withDate,
    selectedProduct,
    searchValue,
    selectedProvince,
    dispatch,
  ]);

  useEffect(() => {
    if (!key) return;

    const isMounted = { current: true };

    const fetchTransportData = async () => {
      try {
        setError(null);
        setIsLoading(true);

        const type = tabValue === "1" ? "in" : "out";

        const response = await dispatch(
          getPoultryTransportByCodeService({
            code: key,
            type: type,
            page: page,
            page_size: perPage,
            date1: withDate && selectedDate1 ? selectedDate1 : "",
            date2: withDate && selectedDate2 ? selectedDate2 : "",
            search: searchValue || "",
            product: selectedProduct || "",
            province: selectedProvince || "",
            from: from,
          })
        );

        if (!isMounted.current) {
          return;
        }

        if (response.error) {
          setError(response.error);
          return;
        }

        const responseData = response.payload?.data ?? { results: [] };
        const results = responseData?.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),
        ]);

        setTableData(mappedTableData);
        setTotalRows(responseData?.count ?? 0);
      } catch (err) {
        console.error("Failed to fetch transport data:", err);
        if (!isMounted.current) {
          return;
        }
        setError(err);
      } finally {
        if (isMounted.current) {
          setIsLoading(false);
        }
      }
    };

    fetchTransportData();

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

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

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

  return (
    <Fragment>
      <Grid container justifyContent="center" xs={12} mt={2}>
        <Grid
          container
          alignItems="center"
          justifyContent="center"
          xs={12}
          mt={2}
        >
          <Tabs
            scrollButtons="auto"
            variant="scrollable"
            allowScrollButtonsMobile
            value={tabValue}
            onChange={handleTabChange}
          >
            <Tab label="بارهای ورودی" value="1" />
            <Tab label="بارهای خروجی" value="2" />
          </Tabs>
        </Grid>
        {dashboardData && (
          <Grid container mt={2} mb={4} isDashboard xs={12}>
            <ResponsiveTable
              noPagination
              isDashboard
              columns={dashboardColumns}
              data={[
                [
                  safeValue(dashboardData?.product),
                  safeValue(formatNumber(dashboardData?.bars)),
                  safeValue(formatNumber(dashboardData?.totalBarsWight)),
                  safeValue(formatNumber(dashboardData?.inputBars)),
                  safeValue(formatNumber(dashboardData?.totalInputBarsWight)),
                  formatPercent(dashboardData?.totalInputBarsPercent),
                  safeValue(formatNumber(dashboardData?.outputBars)),
                  safeValue(formatNumber(dashboardData?.totalOutputBarsWight)),
                  formatPercent(dashboardData?.totalOutputBarsPercent),
                  formatDateTimeFromIso(dashboardData?.lastUpdate),
                ],
              ]}
              title="داشبورد"
            />
          </Grid>
        )}
        <Grid
          container
          alignItems="center"
          justifyContent="center"
          gap={2}
          xs={12}
          mt={2}
          px={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={tabValue === "2" ? "استان مقصد" : "استان مبدا"}
                  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>
            </Grid>
          </Grid>
        </Grid>
        <Grid
          container
          justifyContent="center"
          alignItems="center"
          px={2}
          xs={12}
          mt={2}
        >
          {error && (
            <Grid container justifyContent="center" xs={12}>
              <Typography variant="body1" color="error">
                خطا در دریافت اطلاعات
              </Typography>
            </Grid>
          )}
          {!error && (
            <ResponsiveTable
              columns={columns}
              data={tableData}
              title={tabValue === "1" ? "بارهای ورودی" : "بارهای خروجی"}
              paginated={false}
              handlePageChange={handlePageChange}
              handlePerRowsChange={handlePerRowsChange}
              totalRows={totalRows}
              page={page}
              perPage={perPage}
            />
          )}
        </Grid>
      </Grid>
    </Fragment>
  );
};
