import React, { useContext, useEffect, useState } from "react";
import {
  Grid,
  Box,
  Typography,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  FormHelperText,
  TextField,
  Button,
  Tooltip,
  IconButton,
} from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { AppContext } from "../../../../contexts/AppContext";
import { Line } from "react-chartjs-2";
import { useDispatch } from "react-redux";
import { visorsGetPredictionStaticsChartService } from "../../services/get-visor-prediction-chart";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate } from "../../../../utils/formatTime";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Chart } from "chart.js";
import annotationPlugin from "chartjs-plugin-annotation";
import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye";

import {
  ROUTE_ADMINX_VISOR_STATICS_PREDICTION,
  ROUTE_CITY_VISOR_STATICS_PREDICTION,
  ROUTE_COMMERCE_VISOR_STATICS_PREDICTION,
  ROUTE_OBSERVATORY_VISOR_STATICS_PREDICTION,
  ROUTE_PROVINCE_SUPERVISOR_STATICS_PREDICTION,
  ROUTE_PROVINCEـVISOR_STATICS_PREDICTION,
  ROUTE_SUPER_ADMIN_VISOR_STATICS_PREDICTION,
  ROUTE_VETـSUPERVISOR_STATICS_PREDICTION,
} from "../../../../routes/routes";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import axios from "axios";
Chart.register(annotationPlugin);
export const VisorStaticsPredictionCharts = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const dispatch = useDispatch();

  const [tablesData, setTableData] = useState([]);
  const [originData, setOriginData] = useState([]);

  const [chartData, setChartData] = useState(null);
  const [openNotif] = useContext(AppContext);

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

  const getDetailRoute = (item) => {
    const route =
      getRoleFromUrl() === "AdminX"
        ? ROUTE_ADMINX_VISOR_STATICS_PREDICTION
        : getRoleFromUrl() === "SuperAdmin"
        ? ROUTE_SUPER_ADMIN_VISOR_STATICS_PREDICTION
        : getRoleFromUrl() === "CityOperator"
        ? ROUTE_CITY_VISOR_STATICS_PREDICTION
        : getRoleFromUrl() === "ProvinceOperator"
        ? ROUTE_PROVINCEـVISOR_STATICS_PREDICTION
        : getRoleFromUrl() === "VetSupervisor"
        ? ROUTE_VETـSUPERVISOR_STATICS_PREDICTION
        : getRoleFromUrl() === "Commerce"
        ? ROUTE_COMMERCE_VISOR_STATICS_PREDICTION
        : getRoleFromUrl() === "ProvinceSupervisor"
        ? ROUTE_PROVINCE_SUPERVISOR_STATICS_PREDICTION
        : getRoleFromUrl() === "Observatory"
        ? ROUTE_OBSERVATORY_VISOR_STATICS_PREDICTION
        : ROUTE_ADMINX_VISOR_STATICS_PREDICTION;

    return route + item?.hatchings.join(",").toString() + "/" + item?.date;
  };

  const formik = useFormik({
    initialValues: {
      consumption_limit_type: "",
      killing_age_external_type: "",
      killing_age: "",
      time_frame_type: "all",
      consumption_limit: "",
      killing_age_internal_type: "",
    },
    validationSchema: Yup.object({
      consumption_limit_type: Yup.string()
        .required("این گزینه الزامی است")
        .typeError("لطفا فیلد را به درستی پر کنید!"),
      killing_age_external_type: Yup.string()
        .required("این گزینه الزامی است")
        .typeError("لطفا فیلد را به درستی پر کنید!"),
      consumption_limit: Yup.number()
        .required("این گزینه الزامی است")
        .typeError("لطفا فیلد را به درستی پر کنید!"),
      killing_age: Yup.number().when("killing_age_external_type", {
        is: "manual",
        then: Yup.number()
          .required("این گزینه الزامی است")
          .typeError("لطفا فیلد را به درستی پر کنید!"),
      }),
      ave_kill_age_select: Yup.string().when("ave_kill_age", {
        is: "behavior",
        then: Yup.string()
          .required("این گزینه الزامی است")
          .typeError("لطفا فیلد را به درستی پر کنید!"),
      }),
      killing_age_internal_type: Yup.string().when(
        "killing_age_external_type",
        {
          is: "poultry_ave_killing_age",
          then: Yup.string()
            .required("این گزینه الزامی است")
            .typeError("لطفا فیلد را به درستی پر کنید!"),
        }
      ),
    }),
    onSubmit: (values) => {
      let req = {
        consumption_limit_type: values.consumption_limit_type,
        killing_age_external_type: values.killing_age_external_type,
        killing_age:
          values.killing_age_external_type === "manual"
            ? values.killing_age
            : null,
        time_frame_type: values.time_frame_type,
        consumption_limit: values.consumption_limit,
        killing_age_internal_type:
          values.killing_age_external_type === "poultry_ave_killing_age"
            ? values.killing_age_internal_type
            : null,
        date1: values.time_frame_type === "manual" ? selectedDate1 : null,
        date2: values.time_frame_type === "manual" ? selectedDate2 : null,
        role: getRoleFromUrl(),
      };

      req = Object.fromEntries(
        Object.entries(req).filter(([_, value]) => value !== null)
      );

      dispatch(visorsGetPredictionStaticsChartService(req)).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          setChartData(
            transformData(r.payload.data, formik.values.consumption_limit)
          );
          setOriginData(r.payload.data);

          const d = r.payload.data.map((option, index) => {
            return [
              index + 1,
              formatJustDate(option?.date),
              option?.poultry?.toLocaleString(),
              option?.quantity?.toLocaleString(),
              option?.weight?.toLocaleString(),
              Array.isArray(option?.age)
                ? option.age.map((age, i) => age).join(" - ")
                : option?.age,
              <Tooltip placement="left" title="جزئیات" key={index}>
                <IconButton
                  color="primary"
                  size="small"
                  onClick={() => window.open(getDetailRoute(option), "_blank")}
                >
                  <RemoveRedEyeIcon />
                </IconButton>
              </Tooltip>,
            ];
          });
          setTableData(d);
        }
      });
    },
  });

  const handleDownloadExcel = () => {
    let req = {
      consumption_limit_type: formik.values.consumption_limit_type,
      killing_age_external_type: formik.values.killing_age_external_type,
      killing_age:
        formik.values.killing_age_external_type === "manual"
          ? formik.values.killing_age
          : null,
      time_frame_type: formik.values.time_frame_type,
      consumption_limit: formik.values.consumption_limit,
      killing_age_internal_type:
        formik.values.killing_age_external_type === "poultry_ave_killing_age"
          ? formik.values.killing_age_internal_type
          : null,
      date1: formik.values.time_frame_type === "manual" ? selectedDate1 : null,
      date2: formik.values.time_frame_type === "manual" ? selectedDate2 : null,
      role: getRoleFromUrl(),
    };

    req = Object.fromEntries(
      Object.entries(req).filter(([_, value]) => value !== null)
    );

    const queryString = new URLSearchParams(req).toString();

    return queryString;
  };

  useEffect(() => {
    formik.validateForm();
  }, []);

  const chartOptions = {
    scales: {
      y: {
        beginAtZero: true,
        min: 0,
      },
    },
    onClick: (event, elements) => {
      if (elements.length > 0) {
        const clickedElementIndex = elements[0]?.index;
        let route = getDetailRoute(originData[clickedElementIndex]);
        window.open(route, "_blank");
      }
    },
    plugins: {
      annotation: {
        annotations: {
          line1: {
            type: "line",
            yMin: formik.values.consumption_limit,
            yMax: formik.values.consumption_limit,
            borderColor: "red",
            borderWidth: 2,
            borderDash: [5, 5],
            label: {
              display: true,
              content: "حد مصرف",
              position: "end",
              backgroundColor: "rgba(255, 99, 132, 0.8)",
              font: {
                size: 14,
                weight: "bold",
              },
              padding: 5,
            },
          },
        },
      },
    },
  };

  const transformData = (data, consumptionLimit) => {
    if (data?.length) {
      return {
        labels: data?.map((item) => formatJustDate(item.date)),
        datasets: [
          {
            label:
              formik.values.consumption_limit_type === "quantity"
                ? "حجم موجودی (قطعه)"
                : "وزن موجودی (کیلوگرم)",
            data:
              formik.values.consumption_limit_type === "quantity"
                ? data?.map((item) => item.quantity)
                : data?.map((item) => item.weight),
            borderColor: "rgba(75, 192, 192, 1)",
            backgroundColor: "rgba(75, 192, 192, 0.2)",
            borderWidth: 2,
            pointRadius: 5,
            pointBackgroundColor: "yellow",
            pointHoverRadius: 7,
            fill: true,
            tension: 0.4,
          },
        ],
        annotations: {
          line1: {
            type: "line",
            yMin: consumptionLimit,
            yMax: consumptionLimit,
            borderColor: "rgba(255, 99, 132, 1)",
            borderWidth: 3,
            borderDash: [5, 5],
            label: {
              enabled: true,
              content: "حد مصرف",
              position: "end",
              backgroundColor: "rgba(255, 99, 132, 0.8)",
              font: {
                size: 14,
                weight: "bold",
              },
            },
          },
        },
      };
    } else {
      return null;
    }
  };

  return (
    <Grid
      container
      direction="column"
      justifyContent="center"
      alignItems="center"
    >
      <Box
        width={{ xs: "100%", md: "80%" }}
        sx={{
          p: 3,
          borderRadius: 2,
          boxShadow: 2,
          bgcolor: "background.paper",
        }}
      >
        <Typography
          variant="h6"
          color="primary"
          sx={{ mb: 2, fontWeight: "bold" }}
        >
          پیش بینی موجودی
        </Typography>

        <Grid container spacing={2}>
          {/* مصرف */}
          <Grid item xs={12} md={6}>
            <FormControl
              fullWidth
              error={
                formik.touched.consume_limit &&
                Boolean(formik.errors.consume_limit)
              }
            >
              <InputLabel>حد مصرف</InputLabel>
              <Select
                size="small"
                name="consumption_limit_type"
                value={formik.values.consumption_limit_type}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                error={
                  formik.touched.consumption_limit_type &&
                  Boolean(formik.errors.consumption_limit_type)
                }
              >
                <MenuItem value="quantity">قطعه</MenuItem>
                <MenuItem value="live_weight">وزن زنده</MenuItem>
                <MenuItem value="carcassses_weight">وزن لاشه</MenuItem>
              </Select>
              <FormHelperText>
                {formik.touched.consumption_limit_type &&
                  formik.errors.consumption_limit_type}
              </FormHelperText>
            </FormControl>
          </Grid>

          <Grid item xs={12} md={6}>
            {formik.values.consumption_limit_type && (
              <NumberInput
                size="small"
                allowLeadingZeros
                thousandSeparator=","
                id="consumption_limit"
                name="consumption_limit"
                label={
                  formik.values.consumption_limit_type === "quantity"
                    ? "تعداد (قطعه)"
                    : "وزن (کیلوگرم)"
                }
                variant="outlined"
                value={formik.values.consumption_limit}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                error={
                  formik.touched.consumption_limit &&
                  Boolean(formik.errors.consumption_limit)
                }
                helperText={
                  formik.touched.consumption_limit &&
                  formik.errors.consumption_limit
                }
              />
            )}
          </Grid>

          {/* میانگین سن کشتار */}
          <Grid item xs={12} md={6}>
            <FormControl
              fullWidth
              error={
                formik.touched.killing_age_external_type &&
                Boolean(formik.errors.killing_age_external_type)
              }
            >
              <InputLabel>میانگین سن کشتار *</InputLabel>
              <Select
                size="small"
                name="killing_age_external_type"
                value={formik.values.killing_age_external_type}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              >
                <MenuItem value="poultry_ave_killing_age">
                  رفتار سنی کشتار فارم ها
                </MenuItem>
                <MenuItem value="manual">دستی</MenuItem>
              </Select>
              <FormHelperText>
                {formik.touched.killing_age_external_type &&
                  formik.errors.killing_age_external_type}
              </FormHelperText>
            </FormControl>
          </Grid>

          <Grid item xs={12} md={6}>
            {formik.values.killing_age_external_type && (
              <>
                {formik.values.killing_age_external_type ===
                "poultry_ave_killing_age" ? (
                  <FormControl
                    fullWidth
                    error={
                      formik.touched.killing_age_internal_type &&
                      Boolean(formik.errors.killing_age_internal_type)
                    }
                  >
                    <InputLabel>رفتار سنی کشتار</InputLabel>
                    <Select
                      size="small"
                      name="killing_age_internal_type"
                      value={formik.values.killing_age_internal_type}
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                    >
                      <MenuItem value="poultry">بر اساس کشتار فارم ها</MenuItem>
                      <MenuItem value="province">
                        بر اساس میانگین کشتار استانی
                      </MenuItem>
                    </Select>
                    <FormHelperText>
                      {formik.touched.killing_age_internal_type &&
                        formik.errors.killing_age_internal_type}
                    </FormHelperText>
                  </FormControl>
                ) : (
                  <TextField
                    size="small"
                    fullWidth
                    id="killing_age"
                    label="سن را وارد کنید"
                    value={formik.values.killing_age}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={
                      formik.touched.killing_age &&
                      Boolean(formik.errors.killing_age)
                    }
                    helperText={
                      formik.touched.killing_age && formik.errors.killing_age
                    }
                    variant="outlined"
                  />
                )}
              </>
            )}
          </Grid>

          {/* تاریخ پیش بینی */}
          <Grid item xs={12} md={6}>
            <FormControl
              fullWidth
              error={
                formik.touched.time_frame_type &&
                Boolean(formik.errors.time_frame_type)
              }
            >
              <InputLabel>تاریخ پیش بینی *</InputLabel>
              <Select
                size="small"
                name="time_frame_type"
                value={formik.values.time_frame_type}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              >
                <MenuItem value="all">بدون بازه زمانی</MenuItem>
                <MenuItem value="manual">انتخاب بازه زمانی</MenuItem>
              </Select>
              <FormHelperText>
                {formik.touched.time_frame_type &&
                  formik.errors.time_frame_type}
              </FormHelperText>
            </FormControl>
          </Grid>

          {formik.values.time_frame_type === "manual" && (
            <>
              <Grid item xs={12} md={3}>
                <DatePicker
                  label="از تاریخ"
                  value={selectedDate1}
                  onChange={(e) =>
                    setSelectedDate1(moment(e).format("YYYY-MM-DD"))
                  }
                  renderInput={(params) => (
                    <TextField size="small" fullWidth {...params} />
                  )}
                />
              </Grid>
              <Grid item xs={12} md={3}>
                <DatePicker
                  label="تا تاریخ"
                  value={selectedDate2}
                  onChange={(e) =>
                    setSelectedDate2(moment(e).format("YYYY-MM-DD"))
                  }
                  renderInput={(params) => (
                    <TextField size="small" fullWidth {...params} />
                  )}
                />
              </Grid>
            </>
          )}
        </Grid>

        <Box
          sx={{ mt: 3, display: "flex", justifyContent: "center", gap: "10px" }}
        >
          <Button
            disabled={!formik.isValid}
            variant="contained"
            color="primary"
            sx={{ px: 4, py: 1.5, borderRadius: 2 }}
            onClick={formik.handleSubmit}
          >
            پیمایش
          </Button>
          <Button
            disabled={!formik.isValid}
            variant="contained"
            color="success"
            sx={{ px: 4, py: 1.5, borderRadius: 2 }}
            onClick={() => {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                severity: "success",
              });
              const params = handleDownloadExcel();
              const link = `${axios.defaults.baseURL}poultry_hatching_prediction_chart_excel/?${params}`;
              window.location.href = link;
            }}
          >
            خروجی اکسل
          </Button>
        </Box>
      </Box>

      <Grid container xs={12} my={2}>
        <ResponsiveTable
          columns={[
            "ردیف",
            "تاریخ",
            "تعداد مرغداران",
            "حجم (قطعه)",
            "وزن (کیلوگرم)",
            "سن",
            "عملیات",
          ]}
          data={tablesData}
          title="داده های تجمیعی"
          paginated
        />
      </Grid>

      {chartData && (
        <Grid
          container
          justifyContent="center"
          xs={12}
          sx={{
            p: 3,
            borderRadius: 2,
            boxShadow: 2,
            bgcolor: "background.paper",
            my: 5,
          }}
        >
          <Line data={chartData} options={chartOptions} />
        </Grid>
      )}
    </Grid>
  );
};
