import React, { useContext, useState } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import {
  TextField,
  FormControlLabel,
  Radio,
  RadioGroup,
  Button,
  FormControl,
  FormLabel,
  IconButton,
  FormHelperText,
  Typography,
} from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch } from "react-redux";
import {
  provinceJahadEditHerdService,
  provinceJahadSubmitHerdService,
} from "../../services/province-jahad-submit-herd";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import SearchIcon from "@mui/icons-material/Search";
import { provinceJahadGetSingleRancherService } from "../../services/province-jahad-get-single-rancher";
import { SPACING } from "../../../../data/spacing";

export const ProvicneJahadSubmitHerd = ({
  item,
  updateTable,
  getDashboardData,
  rancherKey,
}) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const [searchedRancherKey, setSearchedRancherKey] = useState(null);
  const formik = useFormik({
    initialValues: {
      herd_code: item?.herdCode || "",
      type: item?.type || "",
      contractor_code: item?.contractorCode || "",
      agent: item?.agent || "",
      unique_identifier: item?.uniqueIdentifier || "",
      gender: item?.gender || "نر",
      userInfoCheck: null,
    },
    validationSchema: Yup.object({
      ...(item && {
        herd_code: Yup.string().required("این فیلد اجباریست!"),
        contractor_code: Yup.string().required("این فیلد اجباریست!"),
      }),
      type: Yup.string().required("این فیلد اجباریست!"),
      agent: Yup.string().required("این فیلد اجباریست!"),
      unique_identifier: Yup.string().required("این فیلد اجباریست!"),
      gender: Yup.string().required("این فیلد اجباریست!"),
    }),
    onSubmit: (values) => {
      if (item) {
        dispatch(
          provinceJahadEditHerdService({
            live_stock_key: item?.key,
            unique_identifier: values.unique_identifier,
            agent: values.agent,
            contractor_code: values.contractor_code,
            gender: values.gender,
            type: values.type,
            herd_code: values.herd_code,
          })
        ).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
            dispatch(DRAWER({ right: false, bottom: false, content: null }));

            updateTable();
            getDashboardData();
          }
        });
      } else {
        dispatch(
          provinceJahadSubmitHerdService({
            unique_identifier: values.unique_identifier,
            agent: values.agent,
            gender: values.gender,
            type: values.type,
            rancher_key: rancherKey || searchedRancherKey?.key,
          })
        ).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
            dispatch(DRAWER({ right: false, bottom: false, content: null }));

            updateTable();
            getDashboardData();
          }
        });
      }
    },
  });

  return (
    <>
      {!rancherKey && !searchedRancherKey ? (
        <Grid>
          <Typography>جستجو کاربر</Typography>
          <Grid mt={SPACING.SMALL} display="flex" width={1}>
            <TextField
              fullWidth
              id="userInfoCheck"
              label="شماره موبایل، کد گله یا کد ملی دامدار"
              variant="outlined"
              value={formik.values.userInfoCheck}
              error={
                formik.touched.userInfoCheck
                  ? Boolean(formik.errors.userInfoCheck)
                  : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.userInfoCheck &&
                Boolean(formik.errors.userInfoCheck)
                  ? formik.errors.userInfoCheck
                  : null
              }
            />

            <IconButton
              disabled={!formik.values.userInfoCheck}
              aria-label="delete"
              color="primary"
              onClick={() => {
                dispatch(
                  provinceJahadGetSingleRancherService({
                    value: formik.values.userInfoCheck,
                  })
                ).then((r) => {
                  if (r.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "کاربر یافت نشد",
                      severity: "error",
                    });
                  } else {
                    setSearchedRancherKey(r.payload.data);
                  }
                });
              }}
            >
              <SearchIcon />
            </IconButton>
          </Grid>
          <FormHelperText>
            شماره موبایل، کد گله یا کد ملی دامدار را وارد کنید
          </FormHelperText>
        </Grid>
      ) : (
        <Grid
          container
          justifyContent="center"
          alignItems="center"
          direction="column"
          gap={2}
        >
          {searchedRancherKey && (
            <Grid
              container
              p={2}
              direction="column"
              gap={1}
              xs={12}
              style={{
                border: "1px solid #d9d9d9",
                borderRadius: "10px",
                padding: "20px",
                backgroundColor: "#f0f0f0",
              }}
            >
              <Grid container gap={1} xs={12}>
                <Typography variant="body">نام دامدای:</Typography>
                <Typography variant="body2" color="primary">
                  {searchedRancherKey?.name}
                </Typography>
              </Grid>
              <Grid container gap={1} xs={12}>
                <Typography variant="body">کد گله:</Typography>
                <Typography variant="body2" color="primary">
                  {searchedRancherKey?.herdCode}
                </Typography>
              </Grid>
              <Grid container gap={1} xs={12}>
                <Typography variant="body">کد اپیدمیولوژیک:</Typography>
                <Typography variant="body2" color="primary">
                  {searchedRancherKey?.epidemiologicalCode}
                </Typography>
              </Grid>
              <Grid container gap={1} xs={12}>
                <Typography variant="body">نام گله:</Typography>
                <Typography variant="body2" color="primary">
                  {searchedRancherKey?.herdName}
                </Typography>
              </Grid>
            </Grid>
          )}

          {item && (
            <TextField
              fullWidth
              id="herd_code"
              name="herd_code"
              label="کد گله"
              value={formik.values.herd_code}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={
                formik.touched.herd_code && Boolean(formik.errors.herd_code)
              }
              helperText={formik.touched.herd_code && formik.errors.herd_code}
            />
          )}

          <TextField
            fullWidth
            id="type"
            name="type"
            label="نوع"
            value={formik.values.type}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.type && Boolean(formik.errors.type)}
            helperText={formik.touched.type && formik.errors.type}
          />

          {item && (
            <TextField
              fullWidth
              id="contractor_code"
              name="contractor_code"
              label="کد پیمانکار"
              value={formik.values.contractor_code}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={
                formik.touched.contractor_code &&
                Boolean(formik.errors.contractor_code)
              }
              helperText={
                formik.touched.contractor_code && formik.errors.contractor_code
              }
            />
          )}

          <TextField
            fullWidth
            id="agent"
            name="agent"
            label="مامور"
            value={formik.values.agent}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.agent && Boolean(formik.errors.agent)}
            helperText={formik.touched.agent && formik.errors.agent}
          />

          <TextField
            fullWidth
            id="unique_identifier"
            name="unique_identifier"
            label="شناسه یکتا دام"
            value={formik.values.unique_identifier}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.unique_identifier &&
              Boolean(formik.errors.unique_identifier)
            }
            helperText={
              formik.touched.unique_identifier &&
              formik.errors.unique_identifier
            }
          />

          <FormControl component="fieldset">
            <FormLabel component="legend">جنسیت</FormLabel>
            <RadioGroup
              row
              id="gender"
              name="gender"
              value={formik.values.gender}
              onChange={formik.handleChange}
            >
              <FormControlLabel value="نر" control={<Radio />} label="نر" />
              <FormControlLabel value="ماده" control={<Radio />} label="ماده" />
            </RadioGroup>
            {formik.touched.gender && formik.errors.gender && (
              <div style={{ color: "red" }}>{formik.errors.gender}</div>
            )}
          </FormControl>

          <Button
            disabled={!formik.isValid}
            type="submit"
            variant="contained"
            color="primary"
            fullWidth
            onClick={formik.handleSubmit}
          >
            ثبت
          </Button>
        </Grid>
      )}
    </>
  );
};
