import React, { useContext, useState } from "react";
import {
  Grid,
  TextField,
  Button,
  Paper,
  IconButton,
  Typography,
  Box,
} from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import { useDispatch } from "react-redux";
import { useFormik } from "formik";
import * as Yup from "yup";

import { citySubmitManageHatchingRenterService } from "../../services/city-submit-manage-hatching-renter";
import { AppContext } from "../../../../contexts/AppContext";
import {
  CLOSE_MODAL,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { cityHatchingDeleteRenterService } from "../../services/city-delete-manage-hatching-renter";

export const CityManageHatchingRenter = ({ item, updateTable, readOnly }) => {
  const [editing, setEditing] = useState(false);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      fullName: item?.tenantFullname || "",
      nationalCode: item?.tenantNationalCode || "",
      phoneNumber: item?.tenantMobile || "",
      city: item?.tenantCity || "",
    },
    validationSchema: Yup.object({
      fullName: Yup.string().required("نام و نام خانوادگی الزامی است"),
      nationalCode: Yup.string()
        .required("کد ملی الزامی است")
        .matches(/^[0-9]{10}$/, "کد ملی باید 10 رقم باشد"),
      phoneNumber: Yup.string()
        .required("شماره تلفن الزامی است")
        .matches(/^[0-9]{11}$/, "شماره تلفن باید 11 رقم باشد"),
      city: Yup.string().required("شهر الزامی است"),
    }),
    onSubmit: (values) => {
      dispatch(LOADING_START());
      dispatch(
        citySubmitManageHatchingRenterService({
          key: item?.key,
          tenant_fullname: values.fullName,
          tenant_national_code: values.nationalCode,
          tenant_mobile: values.phoneNumber,
          tenant_city: values.city,
          has_tenant: true,
        })
      ).then((r) => {
        dispatch(CLOSE_MODAL());
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی پیش آمده است!",
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          formik.resetForm();
          updateTable();
          setEditing(false);
        }
        dispatch(LOADING_END());
      });
    },
    enableReinitialize: true,
  });

  const handleEdit = () => {
    setEditing(true);
  };

  const handleDelete = () => {
    dispatch(LOADING_START());

    dispatch(
      cityHatchingDeleteRenterService({ delete_tenant: true, key: item?.key })
    ).then((r) => {
      dispatch(CLOSE_MODAL());
      if (!r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مستاجر با موفقیت حذف شد.",
          severity: "success",
        });
        formik.resetForm();
        updateTable();
      }
    });
  };

  const hasRenter = item?.hasTenant && item?.tenantFullname;

  return (
    <Grid container spacing={3} direction="column">
      {hasRenter && !editing ? (
        <Grid item>
          <Paper elevation={3}>
            <Box
              p={2}
              display="flex"
              justifyContent="space-between"
              alignItems="center"
            >
              <div>
                <Typography variant="subtitle1">
                  <strong>نام مستاجر:</strong> {item.tenantFullname}
                </Typography>
                <Typography variant="body2">
                  <strong>کد ملی:</strong> {item.tenantNationalCode}
                </Typography>
                <Typography variant="body2">
                  <strong>شماره تلفن:</strong> {item.tenantMobile}
                </Typography>
                <Typography variant="body2">
                  <strong>شهر:</strong> {item.tenantCity}
                </Typography>
              </div>
              {!readOnly && (
                <div>
                  <IconButton onClick={handleEdit} color="primary">
                    <EditIcon />
                  </IconButton>
                  <IconButton onClick={handleDelete} color="error">
                    <DeleteIcon />
                  </IconButton>
                </div>
              )}
            </Box>
          </Paper>
        </Grid>
      ) : (
        <Grid item>
          <Paper elevation={3}>
            <Box p={2} component="form" onSubmit={formik.handleSubmit}>
              <Grid container spacing={2}>
                <Grid item xs={12} md={4}>
                  <TextField
                    fullWidth
                    label="نام و نام خانوادگی"
                    name="fullName"
                    value={formik.values.fullName}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={
                      formik.touched.fullName && Boolean(formik.errors.fullName)
                    }
                    helperText={
                      formik.touched.fullName && formik.errors.fullName
                    }
                    disabled={readOnly}
                  />
                </Grid>
                <Grid item xs={12} md={4}>
                  <TextField
                    fullWidth
                    label="کد ملی"
                    name="nationalCode"
                    value={formik.values.nationalCode}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={
                      formik.touched.nationalCode &&
                      Boolean(formik.errors.nationalCode)
                    }
                    helperText={
                      formik.touched.nationalCode && formik.errors.nationalCode
                    }
                    disabled={readOnly}
                  />
                </Grid>
                <Grid item xs={12} md={4}>
                  <TextField
                    fullWidth
                    label="شماره تلفن"
                    name="phoneNumber"
                    value={formik.values.phoneNumber}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={
                      formik.touched.phoneNumber &&
                      Boolean(formik.errors.phoneNumber)
                    }
                    helperText={
                      formik.touched.phoneNumber && formik.errors.phoneNumber
                    }
                    disabled={readOnly}
                  />
                </Grid>
                <Grid item xs={12} md={4}>
                  <TextField
                    fullWidth
                    label="شهر"
                    name="city"
                    value={formik.values.city}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={formik.touched.city && Boolean(formik.errors.city)}
                    helperText={formik.touched.city && formik.errors.city}
                    disabled={readOnly}
                  />
                </Grid>
              </Grid>

              {!readOnly && (
                <Box mt={2}>
                  <Button
                    type="submit"
                    variant="contained"
                    color="primary"
                    disabled={formik.isSubmitting}
                  >
                    {hasRenter ? "ذخیره تغییرات" : "ثبت اطلاعات"}
                  </Button>
                </Box>
              )}
            </Box>
          </Paper>
        </Grid>
      )}
    </Grid>
  );
};
