import React, { useContext, useEffect, useState, useCallback } 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,
  Autocomplete,
} from "@mui/material";
import BusinessIcon from "@mui/icons-material/Business";
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,
  LOADING_END,
  LOADING_START,
} 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 { provinceGetTypeActivity } from "../../services/provinceGetTypeActivity";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { cityGetProvinces } from "../../../city/services/CityGetProvinces";
import { cityGetCity } from "../../../city/services/city-get-city";

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

const LegalGuildForm = ({
  formik,
  isAdmin,
  typeActivities,
  userType,
  provinces,
  cities,
}) => {
  const IS_STEWARD = userType === "steward";
  const IS_ADMIN = getRoleFromUrl() === "AdminX";
  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.SMALL} p={2}>
        <Grid container spacing={2} xs={12}>
          <Grid item xs={12} md={6}>
            <Grid container gap={SPACING.SMALL}>
              <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={!IS_ADMIN}
                  />
                ) : (
                  <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={IS_STEWARD ? "name" : "unit_name"}
                    name={IS_STEWARD ? "name" : "unit_name"}
                    value={formik.values[IS_STEWARD ? "name" : "unit_name"]}
                    onChange={formik.handleChange}
                    onBlur={formik.handleBlur}
                    error={Boolean(
                      formik.errors[IS_STEWARD ? "name" : "unit_name"]
                    )}
                    helperText={
                      formik.errors[IS_STEWARD ? "name" : "unit_name"]
                    }
                  />
                ) : (
                  <InfoBox
                    icon={BusinessIcon}
                    label="نام واحد"
                    value={formik.values[IS_STEWARD ? "name" : "unit_name"]}
                  />
                )}
              </Grid>
            </Grid>
          </Grid>

          <Grid item xs={12} md={6}>
            <Grid container gap={SPACING.SMALL}>
              <Grid item xs={12}>
                <Autocomplete
                  size="small"
                  style={{ width: "100%" }}
                  disablePortal
                  id="province"
                  value={
                    provinces?.find((p) => p.key === formik.values.province)
                      ? {
                          id: formik.values.province,
                          label: provinces.find(
                            (p) => p.key === formik.values.province
                          )?.name,
                        }
                      : null
                  }
                  options={
                    provinces
                      ? provinces.map((i) => ({
                          id: i.key,
                          label: i.name,
                        }))
                      : []
                  }
                  onChange={(e, value) => {
                    formik.setFieldValue("province", value ? value.id : "");
                    formik.setFieldValue("city", "");
                  }}
                  renderInput={(params) => (
                    <TextField {...params} label={"استان"} />
                  )}
                />
              </Grid>

              <Grid item xs={12}>
                <Autocomplete
                  size="small"
                  minWidth={210}
                  style={{ width: "100%" }}
                  disabled={!formik.values.province}
                  disablePortal
                  id="city"
                  value={
                    cities?.find((c) => c.key === formik.values.city)
                      ? {
                          id: formik.values.city,
                          label: cities.find(
                            (c) => c.key === formik.values.city
                          )?.name,
                        }
                      : null
                  }
                  options={
                    cities
                      ? cities.map((i) => ({ id: i.key, label: i.name }))
                      : []
                  }
                  onChange={(e, value) => {
                    formik.setFieldValue("city", value ? value.id : "");
                  }}
                  renderInput={(params) => (
                    <TextField {...params} label={"شهر"} />
                  )}
                />
              </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 = ({ updateTable, item, userType }) => {
  const [provinceData, setProvinceData] = useState();
  const [cityData, setCityData] = useState();

  const IS_STEWARD = userType === "steward";
  const userInitialValue = {
    national_id: item?.user?.nationalId || "",
    first_name: item?.user?.firstName || "",
    last_name: item?.user?.lastName || "",
    province: "",
    city: "",
    address: "",
    mobile: item?.user?.mobile || "",
    type_activity: item?.typeActivity || "",
  };

  if (IS_STEWARD) {
    userInitialValue["name"] = item?.guilds_name || item?.name;
  } else {
    userInitialValue["unit_name"] = item?.guilds_name || item?.guildsName;
  }

  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [nationalCode, setNationalCode] = useState(
    item?.user?.national_id ||
      item?.national_code ||
      preservedNationalCode ||
      ""
  );
  const [userData, setUserData] = useState(
    item ? userInitialValue : preservedUserData
  );
  const [typeActivities, setTypeActivities] = useState([]);

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

  useEffect(() => {
    if (preservedUserData) {
      setUserData(preservedUserData);
      setNationalCode(preservedNationalCode);
    }

    dispatch(LOADING_START());
    dispatch(cityGetProvinces())
      ?.then((r) => {
        if (r?.payload?.data) {
          setProvinceData(r.payload.data);
        }
      })
      .catch((error) => {
        console.error("Error fetching provinces:", error);
      })
      .finally(() => {
        dispatch(LOADING_END());
      });

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

  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) {
        if (isAdmin) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
          // Admin can create even if user not found
          setUserData(
            IS_STEWARD
              ? {
                  is_real_person: false,
                  first_name: "",
                  last_name: "",
                  national_id: nationalCode,
                  province: "",
                  name: "",
                  mobile: "",
                  type_activity: "",
                }
              : {
                  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) {
        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, IS_STEWARD]);

  const formikIntitialValues = {
    national_id: userData?.national_id || userData?.nationalId || "",
    first_name: userData?.first_name || userData?.firstName || "",
    last_name: userData?.last_name || userData?.lastName || "",
    province: userData?.province || "",
    city: userData?.city || "",
    address: userData?.address || "",
    mobile: userData?.mobile || "",
    type_activity: userData?.type_activity || "",
  };

  if (IS_STEWARD) {
    formikIntitialValues["name"] = userData?.name;
  } else {
    formikIntitialValues["unit_name"] = userData?.unit_name;
  }

  const formik = useFormik({
    initialValues: formikIntitialValues,
    validationSchema: getValidationSchema(),
    enableReinitialize: true,
    validateOnMount: 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: provinceData?.find((p) => p?.key === values.province)?.name,
        address: values.address || "",
        mobile: values.mobile || "",
        city: cityData?.find((c) => c?.key === values.city)?.name,
        type_activity: typeActivityKey, // Send key instead of title
        ...(item?.key && { guilds_key: item.key }), // Include guild key for editing
      };

      if (IS_STEWARD) {
        submitData["name"] = values?.name;
      } else {
        submitData["unit_name"] = values?.unit_name;
      }

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

  useEffect(() => {
    if (formik?.values?.province) {
      dispatch(LOADING_START());
      dispatch(cityGetCity(formik?.values?.province))
        .then((r) => {
          if (r?.payload?.data) {
            setCityData(r.payload.data);
          }
        })
        .catch((error) => {
          console.error("Error fetching cities:", error);
        })
        .finally(() => {
          dispatch(LOADING_END());
        });
    } else {
      setCityData([]);
    }
  }, [formik?.values?.province]);

  useEffect(() => {
    if (item && provinceData && !formik?.values?.province) {
      const provinceName = item?.provinceName;
      if (provinceName) {
        const province = provinceData.find((p) => p?.name === provinceName);
        if (province?.key) {
          formik?.setFieldValue("province", province.key);
        }
      }
    }
  }, [item, provinceData]);

  useEffect(() => {
    if (
      item &&
      cityData?.length &&
      formik?.values?.province &&
      !formik?.values?.city
    ) {
      const cityName = item?.cityName;
      if (cityName) {
        const city = cityData.find((c) => c?.name === cityName);
        if (city?.key) {
          formik?.setFieldValue("city", city.key);
        }
      }
    }
  }, [item, cityData, formik?.values?.province]);

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

  return (
    <LegalGuildForm
      formik={formik}
      isAdmin={isAdmin}
      typeActivities={typeActivities}
      userType={userType}
      provinces={provinceData}
      cities={cityData}
    />
  );
};
