import React from "react";
import {
  TextField,
  Typography,
  RadioGroup,
  FormControl,
  Radio,
  FormControlLabel,
  Select,
  MenuItem,
  InputLabel,
  Checkbox,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import BusinessIcon from "@mui/icons-material/Business";
import PublicIcon from "@mui/icons-material/Public";
import LocationCityIcon from "@mui/icons-material/LocationCity";
import DateRangeIcon from "@mui/icons-material/DateRange";
import ConfirmationNumberIcon from "@mui/icons-material/ConfirmationNumber";
import AccountBalanceIcon from "@mui/icons-material/AccountBalance";
import LocalPostOfficeIcon from "@mui/icons-material/LocalPostOffice";
import PhoneIcon from "@mui/icons-material/Phone";
import BadgeIcon from "@mui/icons-material/Badge";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import HomeIcon from "@mui/icons-material/Home";
import CorporateFareIcon from "@mui/icons-material/CorporateFare";
import { Grid } from "../../../../../components/grid/Grid";
import { SPACING } from "../../../../../data/spacing";
import { LabelField } from "../../../../../components/label-field/LabelField";
import { InfoBox } from "./InfoBox";
import { STATUS_VALUES } from "../constants";
import {
  convertPersianToGregorian,
  convertGregorianToPersian,
} from "../utils/dateUtils";

export const GuildInfoSection = ({
  formik,
  guild,
  guildActive,
  isAdmin,
  cities,
  typeActivities,
  hideTitle = false,
  noGridWrapper = false,
}) => {
  const getForeignerDisplay = (isForeigner) => {
    if (isForeigner === STATUS_VALUES.NO || isForeigner === false)
      return STATUS_VALUES.NO;
    if (isForeigner === STATUS_VALUES.YES || isForeigner === true)
      return STATUS_VALUES.YES;
    return "-";
  };

  const getLicenseExpireDateDisplay = () => {
    return formik.values.license_expire_date || "-";
  };

  const getActiveStatusDisplay = () => {
    const activeValue =
      formik.values.active !== null
        ? formik.values.active
        : guild?.active === true || guildActive === true;
    return activeValue === true ? "فعال" : "غیر فعال";
  };

  const content = (
    <Grid container gap={SPACING.TINY} direction="column">
      {!hideTitle && (
        <Grid item xs={12}>
          <Typography variant="h6" gutterBottom>
            اطلاعات صنفی
          </Typography>
        </Grid>
      )}
      <Grid container xs={12}>
        <Grid
          container
          direction="column"
          xs={12}
          md={6}
          px={SPACING.TINY}
          gap={SPACING.TINY}
        >
          <Grid item xs={12}>
            {isAdmin ? (
              <TextField
                label="نام واحد"
                variant="outlined"
                fullWidth
                id="guild_name"
                name="guild_name"
                value={formik.values.guild_name}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            ) : (
              <InfoBox
                icon={BusinessIcon}
                label="نام واحد"
                value={formik.values.guild_name}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <FormControl fullWidth>
                <InputLabel id="area-activity-select-label">
                  رسته واحد صنفی
                </InputLabel>
                <Select
                  labelId="area-activity-select-label"
                  id="area_activity"
                  name="area_activity"
                  value={formik.values.area_activity || ""}
                  label="رسته واحد صنفی"
                  onChange={(e) => {
                    formik.setFieldValue("area_activity", e.target.value);
                  }}
                  onBlur={formik.handleBlur}
                >
                  {typeActivities.map((activity) => (
                    <MenuItem key={activity.key} value={activity.title}>
                      {activity.title}
                    </MenuItem>
                  ))}
                  {/* Show current value if it doesn't exist in options */}
                  {formik.values.area_activity &&
                    !typeActivities.some(
                      (activity) =>
                        activity.title === formik.values.area_activity
                    ) && (
                      <MenuItem
                        key="current-value"
                        value={formik.values.area_activity}
                      >
                        {formik.values.area_activity}
                      </MenuItem>
                    )}
                </Select>
              </FormControl>
            ) : (
              <InfoBox
                icon={BusinessIcon}
                label="رسته واحد صنفی"
                value={formik.values.area_activity}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <TextField
                label="استان"
                variant="outlined"
                fullWidth
                id="state"
                name="state"
                value={formik.values.state}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            ) : (
              <InfoBox
                icon={PublicIcon}
                label="استان"
                value={formik.values.state}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <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}
                >
                  {cities.map((city) => (
                    <MenuItem key={city.key} value={city.name}>
                      {city.name}
                    </MenuItem>
                  ))}
                  {/* Show current value if it doesn't exist in options */}
                  {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>
            ) : (
              <InfoBox
                icon={LocationCityIcon}
                label="شهرستان"
                value={formik.values.city}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <DatePicker
                label="تاریخ انقضا مجوز"
                value={
                  formik.values.license_expire_date
                    ? moment(
                        convertPersianToGregorian(
                          formik.values.license_expire_date
                        )
                      )
                    : null
                }
                onChange={(newValue) => {
                  if (newValue) {
                    const gregorianDate = moment(newValue).format("YYYY-MM-DD");
                    const persianDate =
                      convertGregorianToPersian(gregorianDate);
                    formik.setFieldValue("license_expire_date", persianDate);
                  } else {
                    formik.setFieldValue("license_expire_date", "");
                  }
                }}
                renderInput={(params) => (
                  <TextField {...params} fullWidth variant="outlined" />
                )}
              />
            ) : (
              <InfoBox
                icon={DateRangeIcon}
                label="تاریخ انقضا مجوز"
                value={getLicenseExpireDateDisplay()}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <TextField
                label="شماره مجوز"
                variant="outlined"
                fullWidth
                id="license_number"
                name="license_number"
                value={formik.values.license_number}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            ) : (
              <InfoBox
                icon={ConfirmationNumberIcon}
                label="شماره مجوز"
                value={formik.values.license_number}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <TextField
                label="نام اتحادیه"
                variant="outlined"
                fullWidth
                id="union_name"
                name="union_name"
                value={formik.values.union_name}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            ) : (
              <InfoBox
                icon={AccountBalanceIcon}
                label="نام اتحادیه"
                value={formik.values.union_name}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <LabelField label="وضعیت">
                <FormControl fullWidth>
                  <RadioGroup
                    row
                    name="active"
                    value={
                      formik.values.active === true
                        ? "true"
                        : formik.values.active === false
                        ? "false"
                        : ""
                    }
                    onChange={(e) => {
                      formik.setFieldValue(
                        "active",
                        e.target.value === "true" ? true : false
                      );
                    }}
                    sx={{ justifyContent: "space-around" }}
                  >
                    <FormControlLabel
                      value="true"
                      control={<Radio />}
                      label="فعال"
                    />
                    <FormControlLabel
                      value="false"
                      control={<Radio />}
                      label="غیر فعال"
                    />
                  </RadioGroup>
                </FormControl>
              </LabelField>
            ) : (
              <InfoBox
                icon={CheckCircleIcon}
                label="وضعیت"
                value={getActiveStatusDisplay()}
              />
            )}
          </Grid>
        </Grid>
        <Grid
          container
          xs={12}
          md={6}
          px={SPACING.TINY}
          direction="column"
          gap={SPACING.TINY}
        >
          <Grid item xs={12}>
            {isAdmin ? (
              <TextField
                label="کد پستی"
                variant="outlined"
                fullWidth
                id="postal_code"
                name="postal_code"
                value={formik.values.postal_code}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            ) : (
              <InfoBox
                icon={LocalPostOfficeIcon}
                label="کد پستی"
                value={formik.values.postal_code}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <TextField
                label="شماره تلفن"
                variant="outlined"
                fullWidth
                id="phone_number"
                name="phone_number"
                value={formik.values.phone_number}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            ) : (
              <InfoBox
                icon={PhoneIcon}
                label="شماره تلفن"
                value={formik.values.phone_number}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <LabelField label="آیا اتباع است؟">
                <FormControl fullWidth>
                  <RadioGroup
                    row
                    name="is_foreigner"
                    value={
                      formik.values.is_foreigner === "بلی" ||
                      formik.values.is_foreigner === true
                        ? "بلی"
                        : formik.values.is_foreigner === "خیر" ||
                          formik.values.is_foreigner === false
                        ? "خیر"
                        : ""
                    }
                    onChange={(e) => {
                      formik.setFieldValue(
                        "is_foreigner",
                        e.target.value === "بلی" ? "بلی" : "خیر"
                      );
                    }}
                    sx={{ justifyContent: "space-around" }}
                  >
                    <FormControlLabel
                      value="بلی"
                      control={<Radio />}
                      label="بلی"
                    />
                    <FormControlLabel
                      value="خیر"
                      control={<Radio />}
                      label="خیر"
                    />
                  </RadioGroup>
                </FormControl>
              </LabelField>
            ) : (
              <InfoBox
                icon={PublicIcon}
                label="آیا اتباع است؟"
                value={getForeignerDisplay(formik.values.is_foreigner)}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <TextField
                label="نام شرکت"
                variant="outlined"
                fullWidth
                id="corporation_name"
                name="corporation_name"
                value={formik.values.corporation_name}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            ) : (
              <InfoBox
                icon={CorporateFareIcon}
                label="نام شرکت"
                value={formik.values.corporation_name}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <TextField
                label="شناسه ملی شرکت"
                variant="outlined"
                fullWidth
                id="guild_national_id"
                name="guild_national_id"
                value={formik.values.guild_national_id}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            ) : (
              <InfoBox
                icon={BadgeIcon}
                label="شناسه ملی شرکت"
                value={formik.values.guild_national_id}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <TextField
                label="وضعیت مجوز"
                variant="outlined"
                fullWidth
                id="license_status"
                name="license_status"
                value={formik.values.license_status}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            ) : (
              <InfoBox
                icon={CheckCircleIcon}
                label="وضعیت مجوز"
                value={formik.values.license_status}
              />
            )}
          </Grid>
          <Grid item xs={12}>
            {isAdmin ? (
              <TextField
                label="آدرس"
                variant="outlined"
                fullWidth
                multiline
                rows={3}
                id="address"
                name="address"
                value={formik.values.address}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              />
            ) : (
              <InfoBox
                icon={HomeIcon}
                label="آدرس"
                value={formik.values.address}
                iconSx={{ mt: 0.5 }}
              />
            )}
          </Grid>
        </Grid>
      </Grid>
      <Grid item xs={12} sx={{ display: "flex", mt: 2, pl: 2, mb: 2 }}>
        {isAdmin ? (
          <>
            <FormControlLabel
              control={
                <Checkbox
                  checked={formik.values.steward || false}
                  onChange={(e) =>
                    formik.setFieldValue("steward", e.target.checked)
                  }
                  name="steward"
                  color="primary"
                />
              }
              label="مباشر"
            />
            <FormControlLabel
              sx={{ ml: 3 }}
              control={
                <Checkbox
                  checked={formik.values.guild || false}
                  onChange={(e) =>
                    formik.setFieldValue("guild", e.target.checked)
                  }
                  name="guild"
                  color="primary"
                />
              }
              label="صنف"
            />
          </>
        ) : (
          <>
            <InfoBox
              icon={CheckCircleIcon}
              label="مباشر"
              value={formik.values.steward ? "بلی" : "خیر"}
            />
            <InfoBox
              icon={CheckCircleIcon}
              label="صنف"
              value={formik.values.guild ? "بلی" : "خیر"}
              sx={{ ml: 3 }}
            />
          </>
        )}
      </Grid>
    </Grid>
  );

  if (noGridWrapper) {
    return <>{content}</>;
  }

  return (
    <Grid item xs={12} lg={6} pr={{ xs: 0, md: 2 }} pl={{ xs: 0, md: 3 }}>
      {content}
    </Grid>
  );
};
