import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import {
  ROUTE_ADMINX_ROUTE_NATIONAL_INFO,
  ROUTE_PROVINCE_SUPERVISOR_ROUTE_NATIONAL_INFO,
  ROUTE_SUPER_ADMIN_ROUTE_NATIONAL_INFO,
} from "../../../../routes/routes";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import { Button, Typography, Box } from "@mui/material";
import { useEffect, useState } from "react";
import {
  Egg as EggIcon,
  Numbers as NumbersIcon,
  LocationCity as CityIcon,
  TrendingUp as TrendingUpIcon,
  TrendingDown as TrendingDownIcon,
  ShowChart as ChartIcon,
  Home as FarmIcon,
  CalendarToday as AgeIcon,
  Info as InfoIcon,
  ArrowForward as ArrowForwardIcon,
} from "@mui/icons-material";
import { provinceNationalFarmManagementInfoDashboardService } from "../../services/province-national-info-farm-management-info-dashboard-service";

export const ProvinceNationalInfoOverview = ({ provinceId }) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [provinceData, setProvinceData] = useState(null);

  useEffect(() => {
    dispatch(
      provinceNationalFarmManagementInfoDashboardService({
        province: provinceId,
      })
    ).then((r) => {
      setProvinceData(r.payload.data);
    });
  }, []);

  const handleNavigate = () => {
    dispatch(CLOSE_MODAL());
    navigate(
      getRoleFromUrl() === "AdminX"
        ? `${ROUTE_ADMINX_ROUTE_NATIONAL_INFO}/${provinceId}`
        : getRoleFromUrl() === "SuperAdmin"
        ? `${ROUTE_SUPER_ADMIN_ROUTE_NATIONAL_INFO}/${provinceId}`
        : `${ROUTE_PROVINCE_SUPERVISOR_ROUTE_NATIONAL_INFO}/${provinceId}`
    );
  };

  const StatItem = ({ icon, label, value, color = "text.primary" }) => (
    <Grid container spacing={1} alignItems="center" sx={{ mb: 1, ml: 1 }}>
      <Grid item sx={{ color: "primary.main" }}>
        {icon}
      </Grid>
      <Grid item xs>
        <Typography
          variant="caption"
          sx={{ display: "flex", alignItems: "center" }}
        >
          <Box component="span" sx={{ fontWeight: "bold", mr: 1, color }}>
            {label}: {value}
          </Box>
        </Typography>
      </Grid>
    </Grid>
  );

  return (
    <Grid container sx={{ justifyContent: "center" }}>
      <Grid
        container
        gap={0.3}
        xs={12}
        style={{ width: "100%", justifyContent: "space-between" }}
      >
        <Grid
          container
          xs={5.7}
          direction="column"
          sx={{
            border: "1px solid #e0e0e0",
            borderRadius: 2,
            boxShadow: 2,
            p: 2,
            backgroundColor: "background.paper",
          }}
        >
          <Typography>کل جوجه ریزی ها</Typography>
          <StatItem
            icon={<FarmIcon fontSize="small" />}
            label="تعداد فارم ها"
            value={provinceData?.poultryCount?.toLocaleString() || 0}
          />
          <StatItem
            icon={<EggIcon fontSize="small" />}
            label="تعداد کل جوجه ریزی"
            value={provinceData?.totalHatchingCount?.toLocaleString() || 0}
          />
          <StatItem
            icon={<ChartIcon fontSize="small" />}
            label="حجم کل جوجه ریزی"
            value={provinceData?.totalHatchingQuantity?.toLocaleString() || 0}
          />
          <StatItem
            icon={<TrendingDownIcon fontSize="small" />}
            label="تلفات"
            value={provinceData?.totalHatchingEvacuation?.toLocaleString() || 0}
            color="error.main"
          />
          <StatItem
            icon={<TrendingDownIcon fontSize="small" />}
            label="درصد تلفات "
            value={
              provinceData?.totalHatchingEvacuationPercent?.toLocaleString() ||
              0
            }
            color="error.main"
          />
          <StatItem
            icon={<NumbersIcon fontSize="small" />}
            label="کشتار شده"
            value={
              provinceData?.totalHatchingKillingQuantity?.toLocaleString() || 0
            }
          />
          <StatItem
            icon={<NumbersIcon fontSize="small" />}
            label="درصد کشتار"
            value={
              provinceData?.totalHatchingKillingQuantityPercent?.toLocaleString() ||
              0
            }
          />
          <StatItem
            icon={<NumbersIcon fontSize="small" />}
            label="مانده در سالن"
            value={provinceData?.totalHatchingLeftOver?.toLocaleString() || 0}
          />
          <StatItem
            icon={<NumbersIcon fontSize="small" />}
            label="درصد مانده در سالن"
            value={
              provinceData?.totalHatchingLeftOverPercent?.toLocaleString() || 0
            }
          />
          <StatItem
            icon={<AgeIcon fontSize="small" />}
            label="میانگین سن کشتار"
            value={Math.floor(provinceData?.totalHatchingKillingAge) || 0}
          />
          <StatItem
            icon={<CityIcon fontSize="small" />}
            label="تعداد شهرستان"
            value={Math.floor(provinceData?.cityCount?.toLocaleString()) || 0}
          />
        </Grid>

        <Grid
          container
          xs={6}
          direction="column"
          sx={{
            border: "1px solid #e0e0e0",
            borderRadius: 2,
            boxShadow: 2,
            p: 2,
            backgroundColor: "background.paper",
          }}
        >
          <Typography> جوجه ریزی های فعال</Typography>

          <StatItem
            icon={<TrendingUpIcon fontSize="small" />}
            label="تعداد جوجه ریزی "
            value={
              Math.floor(
                provinceData?.totalActiveHatchingCount?.toLocaleString()
              ) || 0
            }
            color="success.main"
          />
          <StatItem
            icon={<ChartIcon fontSize="small" color="success" />}
            label="حجم جوجه ریزی "
            value={provinceData?.totalActiveHatchingQuantity?.toLocaleString()}
            color="success.main"
          />

          <StatItem
            icon={<ChartIcon fontSize="small" color="success" />}
            label="تلفات"
            value={provinceData?.totalActiveHatchingEvacuation?.toLocaleString()}
            color="success.main"
          />
          <StatItem
            icon={<ChartIcon fontSize="small" color="success" />}
            label="درصد تلفات   "
            value={Math.floor(
              provinceData?.totalActiveHatchingEvacuationPercent?.toLocaleString()
            )}
            color="success.main"
          />

          <StatItem
            icon={<AgeIcon fontSize="small" />}
            label="کشتار شده     "
            value={
              Math.floor(
                provinceData?.totalActiveHatchingKillingQuantity
              ).toLocaleString() || 0
            }
          />
          <StatItem
            icon={<AgeIcon fontSize="small" />}
            label="درصد کشتار  "
            value={
              Math.floor(
                provinceData?.totalActiveHatchingKillingQuantityPercent
              ) || 0
            }
          />

          <StatItem
            icon={<InfoIcon fontSize="small" />}
            label="مانده در سالن   "
            value={
              provinceData?.totalActiveHatchingLeftOver?.toLocaleString() || 0
            }
          />

          <StatItem
            icon={<InfoIcon fontSize="small" />}
            label="درصد مانده در سالن   "
            value={Math.floor(
              provinceData?.totalActiveHatchingLeftOverPercent?.toLocaleString()
            )}
          />
          <StatItem
            icon={<InfoIcon fontSize="small" />}
            label="میانگین سن کشتار"
            value={
              Math.floor(
                provinceData?.totalActiveHatchingKillingAge
              )?.toLocaleString() || 0
            }
          />
        </Grid>
      </Grid>
      <Grid
        item
        xs={10}
        display="flex"
        justifyContent="center"
        mt={3}
        style={{ width: "95%" }}
      >
        <Button
          variant="contained"
          color="primary"
          fullWidth
          sx={{
            borderRadius: 2,
            fontWeight: "bold",
            py: 1.5,
            boxShadow: 2,
            transition: "all 0.3s ease",
            "&:hover": {
              transform: "translateY(-2px)",
              boxShadow: 4,
            },
          }}
          onClick={handleNavigate}
          endIcon={<ArrowForwardIcon />}
        >
          نمایش جزئیات
        </Button>
      </Grid>
    </Grid>
  );
};
