import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Box,
  Button,
  Divider,
  FormControl,
  FormHelperText,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { Grid } from "../components/grid/Grid";
import { SPACING } from "../data/spacing";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { useFormik } from "formik";
import { Yup } from "../lib/yup/yup";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { inspectorGetReporting } from "../features/inspector/services/inspector-get-reporting";
import { LOADING_END, LOADING_START } from "../lib/redux/slices/appSlice";
import AddIcon from "@mui/icons-material/Add";
import RemoveIcon from "@mui/icons-material/Remove";
import SearchIcon from "@mui/icons-material/Search";
import { AdvancedTable } from "../components/advanced-table/AdvancedTable";
import { AppContext } from "../contexts/AppContext";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { format } from "date-fns-jalali";

const InspectorReporting = () => {
  const [reportData, setReportData] = useState();
  const [tableData, setTableData] = useState();
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      mobile: "",
      fname: "",
      lname: "",
      nationalCode: "",
      nationalId: "",
      address: "",
      unitName: "",
      gisCode: "",
      operationNumber: "",
      halls: "",
      economicCode: "",
      systemCode: "",
      epidemiologicalCode: "",
      capacity: "",
      licenseNumber: "",
      healthCode: "",
      orderCode: "",
      race: "",
    },
    validationSchema: Yup.object({
      mobile: Yup.number().typeError("لطفا عدد وارد کنید!"),
      fname: Yup.string().typeError("فیلد را به درستی وارد کنید!"),
      lname: Yup.string().typeError("فیلد را به درستی وارد کنید!"),
      nationalCode: Yup.number().typeError("لطفا عدد وارد کنید!"),
      nationalId: Yup.number().typeError("لطفا عدد وارد کنید!"),
      address: Yup.string().typeError("فیلد را به درستی وارد کنید!"),
      unitName: Yup.string().typeError("فیلد را به درستی وارد کنید!"),
      race: Yup.string().typeError("فیلد را به درستی وارد کنید!"),
      gisCode: Yup.number().typeError("لطفا عدد وارد کنید!"),
      operationNumber: Yup.number().typeError("لطفا عدد وارد کنید!"),
      halls: Yup.number().typeError("لطفا عدد وارد کنید!"),
      economicCode: Yup.number().typeError("لطفا عدد وارد کنید!"),
      systemCode: Yup.number().typeError("لطفا عدد وارد کنید!"),
      epidemiologicalCode: Yup.number().typeError("لطفا عدد وارد کنید!"),
      capacity: Yup.number().typeError("لطفا عدد وارد کنید!"),
      licenseNumber: Yup.number().typeError("لطفا عدد وارد کنید!"),
      healthCode: Yup.number().typeError("لطفا عدد وارد کنید!"),
      orderCode: Yup.number().typeError("لطفا عدد وارد کنید!"),
    }),
  });

  const formikHatching = useFormik({
    initialValues: {
      hatchingDateFrom: "",
      hatchingDateTo: "",
    },
    validationSchema: Yup.object({
      hatchingDateFrom: Yup.string().typeError("فیلد را به درستی وارد کنید!"),
      hatchingDateTo: Yup.string().typeError("فیلد را به درستی وارد کنید!"),
    }),
  });

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

  const handleValidForm = () => {
    if (formik.isValid && formikHatching.isValid) {
      if (
        Object.values(formik.values).filter((item) => item.length > 0)
          .length === 0 &&
        Object.values(formikHatching.values).filter((item) => item.length > 0)
          .length !== 2
      ) {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  };

  const [expanded, setExpanded] = useState(true);
  const handleChange = () => {
    setExpanded(!expanded);
  };

  const handleClick = () => {
    let values = Object.values(formik.values).filter((item) => item.length > 0);
    let finalValue = "";

    for (let index = 0; index < values.length; index++) {
      finalValue = finalValue + values[index] + ",";
    }
    finalValue = finalValue.substring(0, finalValue.length - 1);

    if (formikHatching.values.hatchingDateFrom) {
      finalValue =
        finalValue +
        "&double_hatching_date=" +
        formikHatching.values.hatchingDateFrom +
        "," +
        formikHatching.values.hatchingDateTo;
    }

    if (formik.values) dispatch(LOADING_START());
    dispatch(inspectorGetReporting(finalValue)).then((r) => {
      dispatch(LOADING_END());
      if (r.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی پیش آمده است!",
          severity: "error",
        });
      } else {
        setReportData(r?.payload.data);
      }
    });
  };

  useEffect(() => {
    if (reportData) {
      const d = reportData.map((item, i) => {
        return [
          i + 1,
          item.unitName,
          item.userprofile?.fullName,
          item.breedingUniqueId,
          item.numberOfHalls,
          item.totalCapacity,
          item.userprofile?.mobile,
          item.userprofile?.province,
          item.userprofile?.city,
          item.hatching?.length,
          item.numberOfParty,
          format(new Date(item?.lastPartyDate), "yyyy/MM/dd"),
          item.gisCode,
          item.economicCode,
          item.samasatUserCode,
          item.unitStatus,
        ];
      });

      setTableData(d);
    }
  }, [reportData]);

  const [addFilter, setAddFilter] = useState(false);

  return (
    <>
      <Box display={"flex"} justifyContent="center">
        <Grid
          container
          direction="column"
          xs={12}
          sm={12}
          md={10}
          lg={10}
          mt={SPACING.MEDIUM}
        >
          <Accordion xs={12} expanded={expanded} onChange={handleChange}>
            <AccordionSummary
              expandIcon={<ExpandMoreIcon />}
              aria-controls="panel1a-content"
              id="panel1a-header"
            >
              <Typography>جستجو</Typography>
            </AccordionSummary>
            <AccordionDetails>
              <Grid container justifyContent="center" gap={SPACING.SMALL}>
                <Grid justifyContent="start" container gap={SPACING.SMALL}>
                  <Grid>
                    <TextField
                      size="small"
                      id="mobile"
                      label="موبایل"
                      value={formik.values.mobile}
                      error={
                        formik.touched.mobile
                          ? Boolean(formik.errors.mobile)
                          : null
                      }
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      helperText={
                        formik.touched.mobile && Boolean(formik.errors.mobile)
                          ? formik.errors.mobile
                          : null
                      }
                      autoComplete="current-password"
                      variant="outlined"
                    />
                  </Grid>
                  <Grid>
                    <TextField
                      size="small"
                      id="fname"
                      label="نام"
                      value={formik.values.fname}
                      error={
                        formik.touched.fname
                          ? Boolean(formik.errors.fname)
                          : null
                      }
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      helperText={
                        formik.touched.fname && Boolean(formik.errors.fname)
                          ? formik.errors.fname
                          : null
                      }
                      autoComplete="current-password"
                      variant="outlined"
                    />
                  </Grid>
                  <Grid>
                    <TextField
                      size="small"
                      id="lname"
                      label="نام خانوادگی"
                      value={formik.values.lname}
                      error={
                        formik.touched.lname
                          ? Boolean(formik.errors.lname)
                          : null
                      }
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      helperText={
                        formik.touched.lname && Boolean(formik.errors.lname)
                          ? formik.errors.lname
                          : null
                      }
                      autoComplete="current-password"
                      variant="outlined"
                    />
                  </Grid>
                  <Grid>
                    <TextField
                      size="small"
                      id="nationalCode"
                      label="کد ملی"
                      value={formik.values.nationalCode}
                      error={
                        formik.touched.nationalCode
                          ? Boolean(formik.errors.nationalCode)
                          : null
                      }
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      helperText={
                        formik.touched.nationalCode &&
                        Boolean(formik.errors.nationalCode)
                          ? formik.errors.nationalCode
                          : null
                      }
                      autoComplete="current-password"
                      variant="outlined"
                    />
                  </Grid>
                  <Grid>
                    <TextField
                      size="small"
                      id="nationalId"
                      label="شماره شناسنامه"
                      value={formik.values.nationalId}
                      error={
                        formik.touched.nationalId
                          ? Boolean(formik.errors.nationalId)
                          : null
                      }
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      helperText={
                        formik.touched.nationalId &&
                        Boolean(formik.errors.nationalId)
                          ? formik.errors.nationalId
                          : null
                      }
                      autoComplete="current-password"
                      variant="outlined"
                    />
                  </Grid>
                  <Grid>
                    <TextField
                      size="small"
                      id="address"
                      label="آدرس"
                      value={formik.values.address}
                      error={
                        formik.touched.address
                          ? Boolean(formik.errors.address)
                          : null
                      }
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      helperText={
                        formik.touched.address && Boolean(formik.errors.address)
                          ? formik.errors.address
                          : null
                      }
                      autoComplete="current-password"
                      variant="outlined"
                    />
                  </Grid>

                  <Grid>
                    <TextField
                      size="small"
                      id="unitName"
                      label="نام واحد"
                      value={formik.values.unitName}
                      error={
                        formik.touched.unitName
                          ? Boolean(formik.errors.unitName)
                          : null
                      }
                      onChange={formik.handleChange}
                      onBlur={formik.handleBlur}
                      helperText={
                        formik.touched.unitName &&
                        Boolean(formik.errors.unitName)
                          ? formik.errors.unitName
                          : null
                      }
                      autoComplete="current-password"
                      variant="outlined"
                    />
                  </Grid>

                  <Grid minWidth={230}>
                    <FormControl size="small">
                      <InputLabel id="demo-simple-select-label">
                        نژاد مرغ
                      </InputLabel>
                      <Select
                        labelId="demo-simple-select-label"
                        id="race"
                        label="نژاد مرغ"
                        value={formik.values.race}
                        error={
                          formik.touched.race
                            ? Boolean(formik.errors.race)
                            : null
                        }
                        onChange={(e) => {
                          formik.setFieldValue("race", e.target.value);
                        }}
                        onBlur={formik.handleBlur}
                      >
                        <MenuItem value={""}>همه</MenuItem>
                        <MenuItem value={"آرین"}>آرین</MenuItem>
                        <MenuItem value={"راس"}>راس</MenuItem>
                        <MenuItem value={"آربراکرز (آپلاس)"}>
                          آربراکرز (آپلاس)
                        </MenuItem>
                        <MenuItem value={"کاب"}>کاب</MenuItem>
                        <MenuItem value={"هوبارد"}>هوبارد</MenuItem>
                        <MenuItem value={"ترکیبی"}>ترکیبی</MenuItem>
                        <MenuItem value={"وارداتی"}>وارداتی</MenuItem>
                      </Select>
                      <FormHelperText>
                        {formik.touched.race && Boolean(formik.errors.race)
                          ? formik.errors.race
                          : null}
                      </FormHelperText>
                    </FormControl>
                  </Grid>

                  {addFilter && (
                    <>
                      <Grid>
                        <TextField
                          size="small"
                          id="gisCode"
                          label="کد gis"
                          value={formik.values.gisCode}
                          error={
                            formik.touched.gisCode
                              ? Boolean(formik.errors.gisCode)
                              : null
                          }
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          helperText={
                            formik.touched.gisCode &&
                            Boolean(formik.errors.gisCode)
                              ? formik.errors.gisCode
                              : null
                          }
                          autoComplete="current-password"
                          variant="outlined"
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          size="small"
                          id="operationNumber"
                          label="شماره گواهی عملیاتی"
                          value={formik.values.operationNumber}
                          error={
                            formik.touched.operationNumber
                              ? Boolean(formik.errors.operationNumber)
                              : null
                          }
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          helperText={
                            formik.touched.operationNumber &&
                            Boolean(formik.errors.operationNumber)
                              ? formik.errors.operationNumber
                              : null
                          }
                          autoComplete="current-password"
                          variant="outlined"
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          size="small"
                          id="halls"
                          label="تعداد سالن"
                          value={formik.values.halls}
                          error={
                            formik.touched.halls
                              ? Boolean(formik.errors.halls)
                              : null
                          }
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          helperText={
                            formik.touched.halls && Boolean(formik.errors.halls)
                              ? formik.errors.halls
                              : null
                          }
                          autoComplete="current-password"
                          variant="outlined"
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          size="small"
                          id="economicCode"
                          label="کد اکونومی"
                          value={formik.values.economicCode}
                          error={
                            formik.touched.economicCode
                              ? Boolean(formik.errors.economicCode)
                              : null
                          }
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          helperText={
                            formik.touched.economicCode &&
                            Boolean(formik.errors.economicCode)
                              ? formik.errors.economicCode
                              : null
                          }
                          autoComplete="current-password"
                          variant="outlined"
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          size="small"
                          id="systemCode"
                          label="کد سیستمی"
                          value={formik.values.systemCode}
                          error={
                            formik.touched.systemCode
                              ? Boolean(formik.errors.systemCode)
                              : null
                          }
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          helperText={
                            formik.touched.systemCode &&
                            Boolean(formik.errors.systemCode)
                              ? formik.errors.systemCode
                              : null
                          }
                          autoComplete="current-password"
                          variant="outlined"
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          size="small"
                          id="epidemiologicalCode"
                          label="کد اپیدمیولوژیک"
                          value={formik.values.epidemiologicalCode}
                          error={
                            formik.touched.epidemiologicalCode
                              ? Boolean(formik.errors.epidemiologicalCode)
                              : null
                          }
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          helperText={
                            formik.touched.epidemiologicalCode &&
                            Boolean(formik.errors.epidemiologicalCode)
                              ? formik.errors.epidemiologicalCode
                              : null
                          }
                          autoComplete="current-password"
                          variant="outlined"
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          size="small"
                          id="capacity"
                          label="ظرفیت کل"
                          value={formik.values.capacity}
                          error={
                            formik.touched.capacity
                              ? Boolean(formik.errors.capacity)
                              : null
                          }
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          helperText={
                            formik.touched.capacity &&
                            Boolean(formik.errors.capacity)
                              ? formik.errors.capacity
                              : null
                          }
                          autoComplete="current-password"
                          variant="outlined"
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          size="small"
                          id="licenseNumber"
                          label="شماره مجوز"
                          value={formik.values.licenseNumber}
                          error={
                            formik.touched.licenseNumber
                              ? Boolean(formik.errors.licenseNumber)
                              : null
                          }
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          helperText={
                            formik.touched.licenseNumber &&
                            Boolean(formik.errors.licenseNumber)
                              ? formik.errors.licenseNumber
                              : null
                          }
                          autoComplete="current-password"
                          variant="outlined"
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          size="small"
                          id="healthCode"
                          label="کد بهداشتی"
                          value={formik.values.healthCode}
                          error={
                            formik.touched.healthCode
                              ? Boolean(formik.errors.healthCode)
                              : null
                          }
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          helperText={
                            formik.touched.healthCode &&
                            Boolean(formik.errors.healthCode)
                              ? formik.errors.healthCode
                              : null
                          }
                          autoComplete="current-password"
                          variant="outlined"
                        />
                      </Grid>

                      <Grid>
                        <TextField
                          size="small"
                          id="orderCode"
                          label="کد سفارش"
                          value={formik.values.orderCode}
                          error={
                            formik.touched.orderCode
                              ? Boolean(formik.errors.orderCode)
                              : null
                          }
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          helperText={
                            formik.touched.orderCode &&
                            Boolean(formik.errors.orderCode)
                              ? formik.errors.orderCode
                              : null
                          }
                          autoComplete="current-password"
                          variant="outlined"
                        />
                      </Grid>
                      <Grid maxWidth={230}>
                        <DatePicker
                          label="جوجه ریزی از"
                          id="hatchingDateFrom"
                          renderInput={(params) => (
                            <TextField size="small" {...params} error={false} />
                          )}
                          value={formikHatching.values.hatchingDateFrom}
                          error={
                            formikHatching.touched.hatchingDateFrom
                              ? Boolean(formikHatching.errors.hatchingDateFrom)
                              : null
                          }
                          onChange={(e) => {
                            formikHatching.setFieldValue(
                              "hatchingDateFrom",
                              moment(e).format("YYYY-MM-DD")
                            );
                          }}
                          onBlur={formikHatching.handleBlur}
                          helperText={
                            formikHatching.touched.hatchingDateFrom &&
                            Boolean(formikHatching.errors.hatchingDateFrom)
                              ? formikHatching.errors.hatchingDateFrom
                              : null
                          }
                        />
                      </Grid>
                      <Grid maxWidth={230}>
                        <DatePicker
                          label="تا"
                          id="hatchingDateTo"
                          renderInput={(params) => (
                            <TextField size="small" {...params} error={false} />
                          )}
                          value={formikHatching.values.hatchingDateTo}
                          error={
                            formikHatching.touched.hatchingDateTo
                              ? Boolean(formikHatching.errors.hatchingDateTo)
                              : null
                          }
                          onChange={(e) => {
                            formikHatching.setFieldValue(
                              "hatchingDateTo",
                              moment(e).format("YYYY-MM-DD")
                            );
                          }}
                          onBlur={formikHatching.handleBlur}
                          helperText={
                            formikHatching.touched.hatchingDateTo &&
                            Boolean(formikHatching.errors.hatchingDateTo)
                              ? formikHatching.errors.hatchingDateTo
                              : null
                          }
                        />
                      </Grid>
                    </>
                  )}
                </Grid>

                <Divider sx={{ width: "100%" }} />

                <Grid>
                  <Button
                    size="small"
                    endIcon={<SearchIcon />}
                    variant="contained"
                    disabled={handleValidForm(formik, formikHatching)}
                    onClick={handleClick}
                  >
                    جستجو
                  </Button>
                </Grid>

                <Grid>
                  <Button
                    variant="contained"
                    endIcon={addFilter ? <RemoveIcon /> : <AddIcon />}
                    onClick={() => {
                      setAddFilter(!addFilter);
                    }}
                    size="small"
                  >
                    {addFilter ? <>کاهش فیلتر</> : <>افزودن فیلتر</>}
                  </Button>
                </Grid>
              </Grid>
            </AccordionDetails>
          </Accordion>
          <Grid container justifyContent="space-between" gap={SPACING.SMALL}>
            <Grid xs={12}>
              <AdvancedTable
                name="گزارشات"
                columns={[
                  "ردیف",
                  "نام واحد",
                  "نام مرغدار",
                  "شناسه یکتا",
                  "تعداد سالن",
                  "ظرفیت",
                  "موبایل",
                  "استان",
                  "شهرستان",
                  "تعداد جوجه ریزی",
                  "تعداد پارتی",
                  "تاریخ آخرین پارتی",
                  "کد gis",
                  "کد اکونومی",
                  "کد سماصط",
                  "وضعیت واحد",
                ]}
                data={tableData}
              />
            </Grid>
          </Grid>
        </Grid>
      </Box>
    </>
  );
};
export default InspectorReporting;
