import React, { useContext, useEffect } from "react";
import {
  Button,
  TextField,
  Tooltip,
  Typography,
  Box,
  Divider,
  Chip,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch, useSelector } from "react-redux";
import { cityGetHatchingInfo } from "../../services/city-get-hatching-info";
import { cityGetHatchingInfoFull } from "../../services/city-get-hatching-info-full";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { AppContext } from "../../../../contexts/AppContext";
import { RiFileExcel2Fill } from "react-icons/ri";
import { useFormik } from "formik";
import axios from "axios";
import { Grid } from "../../../../components/grid/Grid";

export const CityHatchingInfo = () => {
  const { hatchingInfoWithDate, hatchingInfoFull } = useSelector(
    (state) => state.citySlice
  );
  const dispatch = useDispatch();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  useEffect(() => {
    dispatch(cityGetHatchingInfoFull());
  }, []);

  useEffect(() => {
    dispatch(cityGetHatchingInfo({ selectedDate1, selectedDate2 }));
  }, [selectedDate1, selectedDate2]);

  const formik = useFormik({
    initialValues: {
      minAge: "",
      maxAge: "",
    },
  });

  return (
    <Box bgcolor="#f9f9f9" borderRadius={2} boxShadow={3}>
      <Divider style={{ width: "100%" }}>
        <Chip
          label={
            <Typography
              variant="body1"
              gutterBottom
              color="primary"
              fontWeight="bold"
            >
              اطلاعات جوجه ریزی
            </Typography>
          }
        />
      </Divider>

      <Grid container spacing={3} m={0} pb={2}>
        {/* Full Summary Table */}
        <Grid item xs={12}>
          <ResponsiveTable
            noPagination
            title="آمار جوجه ریزی"
            columns={[
              "تعداد فارم",
              "تعداد کل جوجه ریزی",
              "تعداد باقی مانده در سالن",
              "تعداد کشتار شده",
              "وزن کشتار شده",
              "مانده سالن (20 تا 30 روزه)",
              "مانده سالن (30 تا 40 روزه)",
              "مانده سالن (40 تا 50 روزه)",
              "مانده سالن (50 تا 60 روزه)",
              "بیشتر از 60 روزه",
            ]}
            data={[
              [
                hatchingInfoFull?.poultries?.toLocaleString(),
                hatchingInfoFull?.totalHatchingQuantity?.toLocaleString(),
                hatchingInfoFull?.totalHatchingLeftOverQuantity?.toLocaleString(),
                hatchingInfoFull?.totalHatchingKilledQuantity?.toLocaleString(),
                hatchingInfoFull?.totalHatchingKilledWeight?.toLocaleString(),
                hatchingInfoFull?.age2030?.toLocaleString(),
                hatchingInfoFull?.age3040?.toLocaleString(),
                hatchingInfoFull?.age4050?.toLocaleString(),
                hatchingInfoFull?.age5060?.toLocaleString(),
                hatchingInfoFull?.ageMoreThan60?.toLocaleString(),
              ],
            ]}
          />
        </Grid>

        <Divider style={{ width: "100%", marginTop: 8 }}>
          <Chip
            label={
              <Typography
                variant="body1"
                color="primary"
                gutterBottom
                fontWeight="medium"
              >
                بر اساس بازه
              </Typography>
            }
          />
        </Divider>

        <Grid item xs={12} mt={2}>
          <Grid container alignItems="center" spacing={2}>
            <Grid item>
              <DatePicker
                label="از تاریخ"
                renderInput={(params) => (
                  <TextField {...params} size="small" fullWidth />
                )}
                value={selectedDate1}
                onChange={(e) =>
                  setSelectedDate1(moment(e).format("YYYY-MM-DD"))
                }
              />
            </Grid>
            <Grid item>
              <DatePicker
                label="تا تاریخ"
                renderInput={(params) => (
                  <TextField {...params} size="small" fullWidth />
                )}
                value={selectedDate2}
                onChange={(e) =>
                  setSelectedDate2(moment(e).format("YYYY-MM-DD"))
                }
              />
            </Grid>
            <Grid item>
              <Tooltip title="خروجی اکسل">
                <a
                  href={`${axios.defaults.baseURL}hatching_date_range_excel/?date1=${selectedDate1}&date2=${selectedDate2}`}
                  rel="noreferrer"
                >
                  <Button variant="contained" color="success">
                    <RiFileExcel2Fill size={24} />
                  </Button>
                </a>
              </Tooltip>
            </Grid>
          </Grid>
        </Grid>

        <Grid item xs={12}>
          <ResponsiveTable
            noPagination
            title="خلاصه آمار"
            columns={[
              "تعداد فارم های فعال",
              "تعداد کل جوجه ریزی",
              "تعداد باقی مانده در سالن",
              "تعداد کشتار شده",
              "وزن کشتار شده",
            ]}
            data={[
              [
                hatchingInfoWithDate?.poultries?.toLocaleString(),
                hatchingInfoWithDate?.totalHatchingQuantity?.toLocaleString(),
                hatchingInfoWithDate?.totalHatchingLeftOverQuantity?.toLocaleString(),
                hatchingInfoWithDate?.totalHatchingKilledQuantity?.toLocaleString(),
                hatchingInfoWithDate?.totalHatchingKilledWeight?.toLocaleString(),
              ],
            ]}
          />
        </Grid>

        <Divider
          style={{
            width: "100%",
            marginTop: 8,
          }}
          sx={{
            display: { xs: "none", sm: "block" },
          }}
        >
          <Chip
            label={
              <Typography
                variant="body1"
                color="primary"
                gutterBottom
                fontWeight="medium"
                mx="auto"
              >
                گزارش مانده سالن فارم های بیشتر از 10 درصد
              </Typography>
            }
          />
        </Divider>
        <Typography
          variant="body1"
          backgroundColor="rgba(0, 0, 0, 0.08)"
          color="primary"
          gutterBottom
          fontWeight="medium"
          mt={4}
          mx="auto"
          sx={{
            display: { xs: "block", sm: "none" },
            borderRadius: 2,
          }}
          width={{
            xs: "80%",
            sm: "auto",
          }}
        >
          گزارش مانده سالن فارم های بیشتر از 10 درصد
        </Typography>
        <Grid
          item
          xs={12}
          container
          justifyContent="center"
          gap={2}
          alignItems="center"
          mt={4}
          px={1}
        >
          <Grid
            container
            sx={{
              gap: 2,
            }}
            alignItems="center"
          >
            <Grid
              item
              sx={{
                maxWidth: { xs: "46%", sm: "100px" },
              }}
            >
              <TextField
                id="minAge"
                label="از سن"
                variant="outlined"
                size="small"
                value={formik.values.minAge}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            </Grid>
            <Grid
              item
              sx={{
                maxWidth: { xs: "46%", sm: "100px" },
              }}
            >
              <TextField
                id="maxAge"
                label="تا سن"
                variant="outlined"
                size="small"
                value={formik.values.maxAge}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            </Grid>
            <Grid item>
              <Tooltip title="خروجی اکسل">
                <a
                  href={`${axios.defaults.baseURL}hatching_by_age_range/?min_age=${formik.values.minAge}&max_age=${formik.values.maxAge}`}
                  rel="noreferrer"
                >
                  <Button variant="contained" color="success">
                    <RiFileExcel2Fill size={24} />
                  </Button>
                </a>
              </Tooltip>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </Box>
  );
};
