import React from "react";
import { Button, Typography, Checkbox, FormControlLabel } from "@mui/material";
import { Grid } from "../../../../../components/grid/Grid";

/**
 * Extracts the appropriate error message from formik.errors.guilds.
 * guilds can be: string (array-level) | array of guild error objects
 */
const getGuildsErrorMessage = (guildsError) => {
  if (!guildsError) return null;
  if (typeof guildsError === "string") return guildsError;
  if (Array.isArray(guildsError)) {
    for (let i = 0; i < guildsError.length; i++) {
      const guildError = guildsError[i];
      if (!guildError) continue;
      if (typeof guildError === "string") return guildError;
      if (typeof guildError === "object") {
        const firstValue = Object.values(guildError)[0];
        if (typeof firstValue === "string") return firstValue;
        if (typeof firstValue === "object" && firstValue?.message)
          return firstValue.message;
      }
    }
  }
  return null;
};

const MIN_GUILDS_ERROR = "حداقل یک واحد صنفی باید وجود داشته باشد";

/**
 * Collects all blocking error messages to show under submit button.
 * Suppresses "حداقل یک واحد صنفی..." when we have guild data (race condition:
 * formik.values.guilds may lag behind guildsList after inquiry).
 */
const getBlockingErrors = (
  formik,
  isKillHouse,
  isAreaActivityValid,
  guildsCount = 0
) => {
  const errors = [];

  if (formik.errors.isAccepted) {
    errors.push(formik.errors.isAccepted);
  }
  if (formik.errors.national_id) {
    errors.push(formik.errors.national_id);
  }
  if (formik.errors.mobile) {
    errors.push(formik.errors.mobile);
  }
  if (isKillHouse && !isAreaActivityValid) {
    errors.push('رسته واحد صنفی باید شامل کلمه "مرغ" باشد');
  }
  const guildsMsg = getGuildsErrorMessage(formik.errors.guilds);
  if (guildsMsg) {
    if (guildsMsg === MIN_GUILDS_ERROR && guildsCount > 0) {
      // User has guilds from inquiry/edit - suppress stale "no guilds" error
    } else {
      errors.push(guildsMsg);
    }
  }

  return errors;
};

export const FormActions = ({
  formik,
  onClose,
  showCloseButton,
  isKillHouse,
  onSubmit,
  guildsCount = 0
}) => {
  if (showCloseButton) {
    return (
      <Grid item xs={12} mt={4}>
        <Button color="primary" fullWidth variant="contained" onClick={onClose}>
          متوجه شدم
        </Button>
      </Grid>
    );
  }

  const isAreaActivityValid = isKillHouse
    ? formik.values.area_activity && formik.values.area_activity.includes("مرغ")
    : true;

  const guildsErrorRaw = formik.errors.guilds;
  const isStaleMinGuildsError =
    guildsCount > 0 &&
    typeof guildsErrorRaw === "string" &&
    guildsErrorRaw === MIN_GUILDS_ERROR;
  const hasGuildsError = guildsErrorRaw && !isStaleMinGuildsError;
  const hasGuilds =
    (formik.values.guilds && formik.values.guilds.length > 0) ||
    guildsCount > 0;
  const blockingErrors = getBlockingErrors(
    formik,
    isKillHouse,
    isAreaActivityValid,
    guildsCount
  );

  return (
    <>
      <Grid item xs={12}>
        <FormControlLabel
          control={
            <Checkbox
              checked={formik.values.verify_mobile}
              onChange={formik.handleChange}
              name="verify_mobile"
              color="primary"
            />
          }
          label="احراز شماره موبایل"
        />
      </Grid>
      <Grid item xs={12}>
        <Button
          disabled={
            formik.errors.isAccepted ||
            Boolean(formik.errors.national_id) ||
            !isAreaActivityValid ||
            hasGuildsError ||
            !hasGuilds
          }
          color="primary"
          fullWidth
          variant="contained"
          onClick={onSubmit}
          type="button"
        >
          ثبت
        </Button>
        {blockingErrors.length > 0 && (
          <Typography
            component="div"
            variant="caption"
            color="error"
            sx={{ mt: 1, display: "block" }}
          >
            {blockingErrors.map((msg, i) => (
              <span key={i} style={{ display: "block" }}>
                • {msg}
              </span>
            ))}
          </Typography>
        )}
      </Grid>
    </>
  );
};
