import React, {
  useContext,
  useEffect,
  useState,
  useCallback,
  useRef,
} from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { useDispatch } from "react-redux";
import {
  Button,
  TextField,
  Typography,
  Box,
  FormControl,
  Select,
  MenuItem,
  InputLabel,
} from "@mui/material";
import BusinessIcon from "@mui/icons-material/Business";
import PublicIcon from "@mui/icons-material/Public";
import PersonIcon from "@mui/icons-material/Person";
import BadgeIcon from "@mui/icons-material/Badge";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceGetLegalPersonUnitInfoService } from "../../services/province-get-legal-person-unit-info";
import { provinceCreateLegalGuildService } from "../../services/province-create-legal-guild";
import { provinceGetCitiesService } from "../../services/province-get-cities";
import { provinceGetTypeActivity } from "../../services/provinceGetTypeActivity";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

let preservedUserData = null;
let preservedUserFound = false;
let preservedNationalCode = "";

const extractCityFromAddress = (address) => {
  if (!address || typeof address !== "string") {
    return "";
  }

  const cityMatch = address.match(/شهرستان\s+([^\s]+(?:\s+[^\s]+)?)/);
  if (cityMatch && cityMatch[1]) {
    return cityMatch[1].trim();
  }

  const parts = address.split(/\s+/);
  for (let i = 0; i < parts.length; i++) {
    if (parts[i] === "شهرستان" && parts[i + 1]) {
      const cityParts = [];
      if (parts[i + 1]) cityParts.push(parts[i + 1]);
      if (parts[i + 2] && !["بخش", "شهر", "استان"].includes(parts[i + 2])) {
        cityParts.push(parts[i + 2]);
      }
      return cityParts.join(" ");
    }
    if (parts[i] === "شهر" && parts[i + 1]) {
      return parts[i + 1];
    }
  }

  return "";
};

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 = (isAdmin, userFound) =>
  yup.object({
    national_id: yup
      .string()
      .required("شناسه حقوقی الزامی است")
      .matches(/^[0-9]{11}$/, "شناسه حقوقی باید 11 رقم باشد"),
    first_name: isAdmin || !userFound ? yup.string() : yup.string(),
    last_name: isAdmin || !userFound ? yup.string() : yup.string(),
    unit_name: isAdmin || !userFound ? yup.string() : yup.string(),
    province: isAdmin || !userFound ? yup.string() : yup.string(),
    city: yup.string(),
    mobile:
      isAdmin || !userFound
        ? yup
            .string()
            .nullable()
            .test(
              "mobile-format",
              "شماره تلفن باید 11 رقم باشد",
              (value) => !value || /^[0-9]{11}$/.test(value)
            )
        : yup.string(),
    type_activity: isAdmin || !userFound ? yup.string() : yup.string(),
  });

const LegalGuildForm = ({ formik, isAdmin, cities, typeActivities }) => {
  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.SMALL} p={2}>
        <Grid item xs={12}>
          <Typography
            variant="h6"
            style={{
              fontSize: "16px",
            }}
            gutterBottom
          >
            اطلاعات واحد حقوقی
          </Typography>
        </Grid>

        <Grid container spacing={2} xs={12}>
          <Grid item xs={12} md={6}>
            <Grid container direction="column" gap={SPACING.TINY}>
              <Grid item xs={12}>
                {isAdmin ? (
                  <TextField
                    label="شناسه حقوقی"
                    variant="outlined"
                    fullWidth
                    id="national_id"
                    name="national_id"
                    value={formik.values.national_id}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={Boolean(formik.errors.national_id)}
                    helperText={formik.errors.national_id}
                    inputProps={{ maxLength: 11 }}
                    disabled={true}
                  />
                ) : (
                  <InfoBox
                    icon={BadgeIcon}
                    label="شناسه حقوقی"
                    value={formik.values.national_id}
                  />
                )}
              </Grid>

              <Grid item xs={12}>
                {isAdmin ? (
                  <TextField
                    label="نام"
                    variant="outlined"
                    fullWidth
                    id="first_name"
                    name="first_name"
                    value={formik.values.first_name}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={Boolean(formik.errors.first_name)}
                    helperText={formik.errors.first_name}
                  />
                ) : (
                  <InfoBox
                    icon={PersonIcon}
                    label="نام"
                    value={formik.values.first_name}
                  />
                )}
              </Grid>

              <Grid item xs={12}>
                {isAdmin ? (
                  <TextField
                    label="نام خانوادگی"
                    variant="outlined"
                    fullWidth
                    id="last_name"
                    name="last_name"
                    value={formik.values.last_name}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={Boolean(formik.errors.last_name)}
                    helperText={formik.errors.last_name}
                  />
                ) : (
                  <InfoBox
                    icon={PersonIcon}
                    label="نام خانوادگی"
                    value={formik.values.last_name}
                  />
                )}
              </Grid>

              <Grid item xs={12}>
                {isAdmin ? (
                  <TextField
                    label="نام واحد"
                    variant="outlined"
                    fullWidth
                    id="unit_name"
                    name="unit_name"
                    value={formik.values.unit_name}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={Boolean(formik.errors.unit_name)}
                    helperText={formik.errors.unit_name}
                  />
                ) : (
                  <InfoBox
                    icon={BusinessIcon}
                    label="نام واحد"
                    value={formik.values.unit_name}
                  />
                )}
              </Grid>
            </Grid>
          </Grid>

          <Grid item xs={12} md={6}>
            <Grid container direction="column" gap={SPACING.TINY}>
              <Grid item xs={12}>
                {isAdmin ? (
                  <TextField
                    label="استان"
                    variant="outlined"
                    fullWidth
                    id="province"
                    name="province"
                    value={formik.values.province}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={Boolean(formik.errors.province)}
                    helperText={formik.errors.province}
                  />
                ) : (
                  <InfoBox
                    icon={PublicIcon}
                    label="استان"
                    value={formik.values.province}
                  />
                )}
              </Grid>

              <Grid item xs={12}>
                <FormControl fullWidth>
                  <InputLabel id="city-select-label">شهرستان</InputLabel>
                  <Select
                    labelId="city-select-label"
                    id="city"
                    name="city"
                    value={formik.values.city || ""}
                    label="شهرستان"
                    onChange={(e) => {
                      formik.setFieldValue("city", e.target.value);
                    }}
                    onBlur={formik.handleBlur}
                    disabled={false}
                  >
                    {cities.map((city) => (
                      <MenuItem key={city.key} value={city.name}>
                        {city.name}
                      </MenuItem>
                    ))}
                    {formik.values.city &&
                      !cities.some(
                        (city) => city.name === formik.values.city
                      ) && (
                        <MenuItem
                          key="current-value"
                          value={formik.values.city}
                        >
                          {formik.values.city}
                        </MenuItem>
                      )}
                  </Select>
                </FormControl>
              </Grid>

              <Grid item xs={12}>
                <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 item xs={12}>
                {isAdmin ? (
                  <FormControl fullWidth>
                    <InputLabel id="type-activity-select-label">
                      نوع فعالیت
                    </InputLabel>
                    <Select
                      labelId="type-activity-select-label"
                      id="type_activity"
                      name="type_activity"
                      value={formik.values.type_activity || ""}
                      label="نوع فعالیت"
                      onChange={(e) => {
                        formik.setFieldValue("type_activity", e.target.value);
                      }}
                      onBlur={formik.handleBlur}
                    >
                      {typeActivities.map((activity) => (
                        <MenuItem key={activity.key} value={activity.title}>
                          {activity.title}
                        </MenuItem>
                      ))}
                      {formik.values.type_activity &&
                        !typeActivities.some(
                          (activity) =>
                            activity.title === formik.values.type_activity
                        ) && (
                          <MenuItem
                            key="current-value"
                            value={formik.values.type_activity}
                          >
                            {formik.values.type_activity}
                          </MenuItem>
                        )}
                    </Select>
                  </FormControl>
                ) : (
                  <InfoBox
                    icon={BusinessIcon}
                    label="نوع فعالیت"
                    value={formik.values.type_activity}
                  />
                )}
              </Grid>
            </Grid>
          </Grid>
        </Grid>

        <Grid item xs={12} mt={2}>
          <Button
            type="submit"
            variant="contained"
            color="primary"
            fullWidth
            disabled={!formik.isValid}
          >
            ثبت
          </Button>
        </Grid>
      </Grid>
    </form>
  );
};

const InquiryForm = ({ onInquiry, nationalCode, setNationalCode }) => {
  return (
    <Grid container gap={SPACING.SMALL} p={2}>
      <Grid item xs={12}>
        <TextField
          label="شناسه حقوقی"
          variant="outlined"
          fullWidth
          value={nationalCode}
          onChange={(e) => setNationalCode(e.target.value)}
          placeholder="شناسه حقوقی 11 رقمی را وارد کنید"
          inputProps={{ maxLength: 11 }}
        />
      </Grid>
      <Grid item xs={12}>
        <Button
          color="primary"
          fullWidth
          variant="contained"
          onClick={onInquiry}
          disabled={!nationalCode || nationalCode.length !== 11}
        >
          استعلام
        </Button>
      </Grid>
    </Grid>
  );
};

export const ProvinceLegalGuildsForm = ({ onClose, updateTable, guild }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [nationalCode, setNationalCode] = useState(
    guild?.user?.national_id ||
      guild?.national_code ||
      preservedNationalCode ||
      ""
  );
  const [userData, setUserData] = useState(
    guild
      ? {
          national_id: guild?.user?.national_id || guild?.national_code || "",
          first_name: guild?.user?.first_name || "",
          last_name: guild?.user?.last_name || "",
          unit_name: guild?.guilds_name || "",
          province: guild?.address?.province?.name || "",
          city: guild?.address?.city?.name || "",
          address: guild?.address?.address || "",
          mobile: guild?.user?.mobile || "",
          type_activity: guild?.type_activity || "",
        }
      : preservedUserData
  );
  const [userFound, setUserFound] = useState(guild ? true : preservedUserFound);
  const [cities, setCities] = useState([]);
  const [typeActivities, setTypeActivities] = useState([]);

  const currentRole = getRoleFromUrl();
  const isAdmin = currentRole === "AdminX";

  useEffect(() => {
    dispatch(provinceGetCitiesService()).then((r) => {
      setCities(r.payload.data || []);
    });
    dispatch(provinceGetTypeActivity()).then((r) => {
      setTypeActivities(r.payload.data || []);
    });
  }, [dispatch]);

  // Restore preserved data on mount
  useEffect(() => {
    if (preservedUserData) {
      setUserData(preservedUserData);
      setUserFound(preservedUserFound);
      setNationalCode(preservedNationalCode);
    }
  }, []);

  // Update modal size when userData is available (only once)
  const sizeUpdatedRef = useRef(false);
  useEffect(() => {
    if (userData && !sizeUpdatedRef.current) {
      sizeUpdatedRef.current = true;
      // Preserve state before remount
      preservedUserData = userData;
      preservedUserFound = userFound;
      preservedNationalCode = nationalCode;
      // Update modal with larger size
      dispatch(
        OPEN_MODAL({
          title: "ثبت واحد حقوقی",
          content: (
            <ProvinceLegalGuildsForm
              onClose={onClose}
              updateTable={updateTable}
            />
          ),
          size: { xs: "96vw", md: "90vw", lg: "600px" },
        })
      );
    }
  }, [userData, dispatch, onClose, updateTable, userFound, nationalCode]);

  const handleInquiry = useCallback(() => {
    if (!nationalCode || nationalCode.length !== 11) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "لطفا شناسه حقوقی 11 رقمی معتبر وارد کنید",
        severity: "error",
      });
      return;
    }

    dispatch(provinceGetLegalPersonUnitInfoService(nationalCode)).then((r) => {
      if (r.payload.error) {
        setUserFound(false);
        if (isAdmin) {
          // Admin can create even if user not found
          setUserData({
            is_real_person: false,
            first_name: "",
            last_name: "",
            national_id: nationalCode,
            province: "",
            unit_name: "",
            mobile: "",
            type_activity: "",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        }
      } else if (r.payload.data) {
        setUserFound(true);
        const extractedCity = extractCityFromAddress(
          r.payload.data.address || ""
        );
        setUserData({
          ...r.payload.data,
          city: extractedCity,
        });
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "اطلاعات با موفقیت دریافت شد",
          severity: "success",
        });
      }
    });
  }, [dispatch, nationalCode, openNotif, isAdmin]);

  const formik = useFormik({
    initialValues: {
      national_id: userData?.national_id || userData?.nationalId || "",
      first_name: userData?.first_name || userData?.firstName || "",
      last_name: userData?.last_name || userData?.lastName || "",
      unit_name: userData?.unit_name || userData?.unitName || "",
      province: userData?.province || "",
      city: userData?.city || "",
      address: userData?.address || "",
      mobile: userData?.mobile || "",
      type_activity: userData?.type_activity || "",
    },
    validationSchema: getValidationSchema(isAdmin, userFound),
    enableReinitialize: true,
    onSubmit: (values) => {
      // Find type_activity key from the title
      const typeActivityObj = typeActivities.find(
        (activity) => activity.title === values.type_activity
      );
      const typeActivityKey = typeActivityObj?.key || "";

      const submitData = {
        first_name: values.first_name,
        last_name: values.last_name,
        national_id: values.national_id,
        province: values.province,
        address: values.address || "",
        unit_name: values.unit_name,
        mobile: values.mobile || "",
        city: values.city,
        type_activity: typeActivityKey, // Send key instead of title
        ...(guild?.key && { guilds_key: guild.key }), // Include guild key for editing
      };

      dispatch(provinceCreateLegalGuildService(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());
        }
      });
    },
  });

  if (!userData && !guild) {
    return (
      <InquiryForm
        onInquiry={handleInquiry}
        nationalCode={nationalCode}
        setNationalCode={setNationalCode}
      />
    );
  }

  return (
    <LegalGuildForm
      formik={formik}
      isAdmin={isAdmin}
      cities={cities}
      typeActivities={typeActivities}
    />
  );
};
