import React, { useContext } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { useDispatch } from "react-redux";
import { Button, TextField, Typography, Box } from "@mui/material";
import PersonIcon from "@mui/icons-material/Person";
import PublicIcon from "@mui/icons-material/Public";
import BadgeIcon from "@mui/icons-material/Badge";
import CalendarTodayIcon from "@mui/icons-material/CalendarToday";
import AccountBoxIcon from "@mui/icons-material/AccountBox";
import BusinessIcon from "@mui/icons-material/Business";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { slaughterHouseEditDispenserService } from "../../services/slaughter-house-submit-dispenser-service";

const InfoBox = ({ icon: Icon, label, value, iconSx }) => (
  <Box
    display="flex"
    alignItems={iconSx ? "flex-start" : "center"}
    gap={1}
    px={1.5}
    py={0.5}
    bgcolor="#f5f5f5"
    borderRadius={1}
  >
    <Icon color="action" sx={iconSx} />
    <Box>
      <Typography variant="caption" color="text.secondary">
        {label}
      </Typography>
      <Typography variant="body1">{value || "-"}</Typography>
    </Box>
  </Box>
);

const getValidationSchema = () =>
  yup.object({
    mobile: yup
      .string()
      .required("شماره همراه الزامی است")
      .matches(/^09\d{9}$/, "شماره تلفن باید با 09 شروع شود و 11 رقم باشد"),
  });

const DispenserForm = ({ formik, userInfo }) => {
  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.SMALL} p={2}>
        {userInfo && (
          <Grid container spacing={2} xs={12} mb={2}>
            <Grid item xs={12}>
              <Typography
                variant="subtitle2"
                color="text.secondary"
                gutterBottom
                sx={{ mb: 1 }}
              >
                اطلاعات شخصی
              </Typography>
            </Grid>
            <Grid item xs={12} md={4}>
              <InfoBox
                icon={BadgeIcon}
                label="کد ملی"
                value={formik.values.nationalId}
              />
            </Grid>
            <Grid item xs={12} md={4}>
              <InfoBox
                icon={PersonIcon}
                label="نام پدر"
                value={userInfo.fatherName}
              />
            </Grid>
            <Grid item xs={12} md={4}>
              <InfoBox
                icon={CalendarTodayIcon}
                label="تاریخ تولد"
                value={userInfo.birthday}
              />
            </Grid>

            <Grid item xs={12} md={4}>
              <InfoBox
                icon={AccountBoxIcon}
                label="جنسیت"
                value={userInfo.gender ? "مرد" : "زن"}
              />
            </Grid>

            <Grid item xs={12} md={4}>
              <InfoBox
                icon={BadgeIcon}
                label="شماره شناسنامه"
                value={userInfo.nationalCode}
              />
            </Grid>
          </Grid>
        )}

        <Grid container spacing={2} xs={12}>
          <Grid item xs={12} md={4}>
            <InfoBox
              icon={PersonIcon}
              label="نام"
              value={formik.values.first_name}
            />
          </Grid>

          <Grid item xs={12} md={4}>
            <InfoBox
              icon={PersonIcon}
              label="نام خانوادگی"
              value={formik.values.last_name}
            />
          </Grid>

          <Grid item xs={12} md={4}>
            <InfoBox icon={PublicIcon} label="شهر" value={formik.values.city} />
          </Grid>

          <Grid item xs={12} md={4}>
            <InfoBox
              icon={BusinessIcon}
              label="نوع توزیع کننده"
              value={
                formik.values.dispenser_type === "inductor"
                  ? "واسطه"
                  : formik.values.dispenser_type === "salesman"
                  ? "فروشنده"
                  : formik.values.dispenser_type === "driver"
                  ? "راننده"
                  : formik.values.dispenser_type
              }
            />
          </Grid>

          {formik.values.dispenser_type === "driver" && (
            <>
              <Grid item xs={12} md={4}>
                <InfoBox
                  icon={BusinessIcon}
                  label="نوع خودرو"
                  value={formik.values.driver_car_type}
                />
              </Grid>
              {formik.values.pelak && (
                <Grid item xs={12} md={4}>
                  <InfoBox
                    icon={BadgeIcon}
                    label="پلاک خودرو"
                    value={formik.values.pelak}
                  />
                </Grid>
              )}
            </>
          )}

          <Grid item xs={12} md={4}>
            <InfoBox
              icon={BusinessIcon}
              label="سقف محدودیت"
              value={formik.values.limitation_amount || 0}
            />
          </Grid>
          <Grid item xs={12} md={4}>
            <TextField
              label="شماره همراه"
              variant="outlined"
              fullWidth
              id="mobile"
              name="mobile"
              value={formik.values.mobile}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={Boolean(formik.errors.mobile)}
              helperText={formik.errors.mobile}
              inputProps={{ maxLength: 11 }}
            />
          </Grid>
        </Grid>

        <Grid item xs={12} mt={2}>
          <Button
            type="submit"
            variant="contained"
            color="primary"
            fullWidth
            disabled={!formik.isValid}
          >
            ویرایش
          </Button>
        </Grid>
      </Grid>
    </form>
  );
};

export const AllDispensersEditForm = ({ item, updateTable }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const nationalId = item?.user?.nationalId || item?.user?.nationalCode;

  // Extract userInfo from item.user object
  const userInfo = item?.user
    ? {
        nationalCode: item.user.nationalId || item.user.nationalCode || null,
        fatherName: item.user.fatherName || null,
        birthday: item.user.birthday || null,
        gender: item.user.gender,
        identityNo: item.user.identityNo || null,
        identitySeries: item.user.identitySeries || null,
        identitySerial: item.user.identitySerial || null,
      }
    : null;

  const formik = useFormik({
    initialValues: {
      first_name: item?.user?.firstName || "",
      last_name: item?.user?.lastName || "",
      mobile: item?.user?.mobile || "",
      city: item?.user?.cityName || "",
      national_id: nationalId || "",
      dispenser_type: item?.dispenserType || "inductor",
      limitation_amount: item?.limitationAmount || 0,
      driver_car_type: item?.car || "",
      pelak: item?.pelak || "",
    },
    enableReinitialize: true,
    validationSchema: getValidationSchema(),
    onSubmit: (values) => {
      const submitData = {
        key: item?.key,
        mobile: values.mobile,
      };

      dispatch(slaughterHouseEditDispenserService(submitData)).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",
          });
          if (updateTable) {
            updateTable();
          }
          dispatch(CLOSE_MODAL());
        }
      });
    },
  });

  return <DispenserForm formik={formik} userInfo={userInfo} />;
};
