import React, { useContext, useEffect, useState } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import {
  Radio,
  RadioGroup,
  FormControlLabel,
  TextField,
  Button,
  Grid,
  Container,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from "@mui/material";
import { useDispatch } from "react-redux";
import { provinceSmsSetAnnouncement } from "../../services/province-sms-set-announcement";
import { AppContext } from "../../../../contexts/AppContext";
import { getAnnouncement } from "../../../authentication/services/get-announcement";

export const ProvinceSmsAnnouncement = () => {
  const [openNotif] = useContext(AppContext);
  const [target, setTarget] = useState(0);
  const [data, setData] = useState([]);

  const handleChange = (event) => {
    setTarget(event.target.value);
  };
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getAnnouncement()).then((r) => {
      setData(r.payload.data);
      formik.setFieldValue(
        "status",
        r.payload.data[0]?.active === true ? "true" : "false"
      );
      formik.setFieldValue("announcement", r.payload.data[0]?.description);
    });
  }, []);

  const initialValues = {
    status: "",
    announcement: "",
  };

  const validationSchema = Yup.object().shape({
    status: Yup.string().required("لطفا وضعیت را انتخاب کنید"),
    announcement: Yup.string().when("status", {
      is: "true",
      then: Yup.string().required("لطفا متن اعلان را وارد کنید!"),
    }),
  });

  useEffect(() => {
    if (data.length) {
      formik.setFieldValue(
        "status",
        data[target].active === true ? "true" : "false"
      );
      if (data[target].description) {
        formik.setFieldValue("announcement", data[target].description);
      } else {
        formik.setFieldValue("announcement", "");
      }
    }
  }, [target]);

  const onSubmit = (values) => {
    dispatch(
      provinceSmsSetAnnouncement({
        active: values.status === "true" ? true : false,
        description: values.announcement,
        key: data[target].key,
      })
    ).then((r) => {
      if (r.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی پیش آمده است!",
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  const formik = useFormik({
    initialValues,
    validationSchema,
    onSubmit,
  });

  return (
    <Container maxWidth="md">
      <div
        style={{
          backgroundColor: "#ffffff",
          padding: "20px",
          borderRadius: "4px",
          boxShadow: "0px 4px 10px rgba(0, 0, 0, 0.1)",
          transition: "box-shadow 0.3s ease",
          ":hover": { boxShadow: "0px 8px 20px rgba(0, 0, 0, 0.2)" },
        }}
      >
        <form onSubmit={formik.handleSubmit}>
          <Grid container spacing={3}>
            <Grid container item xs={12} alignItems="center">
              <Grid item xs={12} sm={6}>
                <FormControl>
                  <InputLabel id="demo-simple-select-label">مقصد</InputLabel>
                  <Select
                    labelId="demo-simple-select-label"
                    id="demo-simple-select"
                    value={target}
                    label="مقصد"
                    onChange={handleChange}
                    size="small"
                  >
                    <MenuItem value={0}>کشتارگاه</MenuItem>
                    <MenuItem value={1}>شهرستان</MenuItem>
                  </Select>
                </FormControl>
              </Grid>
            </Grid>
            <Grid item xs={12}>
              <RadioGroup
                row
                aria-label="status"
                name="status"
                value={formik.values.status}
                onChange={formik.handleChange}
              >
                <FormControlLabel
                  value="true"
                  control={<Radio />}
                  label="فعال"
                />
                <FormControlLabel
                  value="false"
                  control={<Radio />}
                  label="غیر فعال"
                />
              </RadioGroup>
            </Grid>
            {formik.values.status === "true" && (
              <Grid item xs={12}>
                <TextField
                  id="announcement"
                  name="announcement"
                  label="متن اعلان"
                  multiline
                  rows={4}
                  fullWidth
                  variant="outlined"
                  value={formik.values.announcement}
                  onChange={formik.handleChange}
                  error={
                    formik.touched.announcement &&
                    Boolean(formik.errors.announcement)
                  }
                  helperText={
                    formik.touched.announcement && formik.errors.announcement
                  }
                />
              </Grid>
            )}
            <Grid item xs={12}>
              <Button
                type="submit"
                variant="contained"
                color="primary"
                style={{ marginTop: "16px" }}
              >
                ثبت
              </Button>
            </Grid>
          </Grid>
        </form>
      </div>
    </Container>
  );
};
