import React from "react";
import {
  TextField,
  Typography,
  RadioGroup,
  FormControl,
  Radio,
  FormControlLabel,
  Autocomplete,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import PersonIcon from "@mui/icons-material/Person";
import PhoneIcon from "@mui/icons-material/Phone";
import BadgeIcon from "@mui/icons-material/Badge";
import CakeIcon from "@mui/icons-material/Cake";
import FaceIcon from "@mui/icons-material/Face";
import LocationCityIcon from "@mui/icons-material/LocationCity";
import FavoriteIcon from "@mui/icons-material/Favorite";
import { Grid } from "../../../../../components/grid/Grid";
import { SPACING } from "../../../../../data/spacing";
import { LabelField } from "../../../../../components/label-field/LabelField";
import { InfoBox } from "./InfoBox";
import { GENDER_VALUES, ALIVE_STATUS } from "../constants";
import {
  convertPersianToGregorian,
  convertGregorianToPersian,
} from "../utils/dateUtils";

export const PersonalInfoSection = ({
  formik,
  guild,
  hasInquiry,
  isAdmin,
  isSuperAdmin,
  isKillHouse,
  cities = [],
}) => {
  const getGenderDisplay = (gender) => {
    if (gender === "True" || gender === true) return GENDER_VALUES.MALE;
    if (gender === "False" || gender === false) return GENDER_VALUES.FEMALE;
    return "-";
  };

  const getAliveStatusDisplay = (isAlive) => {
    if (isAlive === ALIVE_STATUS.YES || isAlive === true)
      return ALIVE_STATUS.YES;
    if (isAlive === ALIVE_STATUS.NO || isAlive === false)
      return ALIVE_STATUS.NO;
    return "-";
  };

  const getBirthDateDisplay = () => {
    return formik.values.birth_date || "-";
  };

  return (
    <Grid
      item
      xs={12}
      lg={6}
      pl={{ xs: 0, md: 2 }}
      pr={{ xs: 0, md: 3 }}
      mb={2}
    >
      <Grid container gap={SPACING.SMALL}>
        <Grid item xs={12}>
          <Typography variant="h6" gutterBottom>
            اطلاعات شخصی
          </Typography>
        </Grid>
        <Grid container xs={12}>
          <Grid container xs={12} md={6} gap={SPACING.TINY} px={SPACING.TINY}>
            <Grid item xs={12}>
              {guild || 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: 10 }}
                  disabled={!isAdmin || isKillHouse}
                />
              ) : (
                <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}
                />
              ) : (
                <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}
                />
              ) : (
                <InfoBox
                  icon={PersonIcon}
                  label="نام خانوادگی"
                  value={formik.values.last_name}
                />
              )}
            </Grid>
            <Grid item xs={12}>
              {isAdmin ? (
                <TextField
                  label="شماره شناسنامه"
                  variant="outlined"
                  fullWidth
                  id="national_code"
                  name="national_code"
                  value={formik.values.national_code}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                />
              ) : (
                <InfoBox
                  icon={BadgeIcon}
                  label="شماره شناسنامه"
                  value={formik.values.national_code}
                />
              )}
            </Grid>
            <Grid item xs={12}>
              {isAdmin ? (
                <LabelField label="در قید حیات">
                  <FormControl fullWidth>
                    <RadioGroup
                      row
                      name="is_alive"
                      value={
                        formik.values.is_alive === "بلی" ||
                        formik.values.is_alive === true
                          ? "بلی"
                          : formik.values.is_alive === "خیر" ||
                            formik.values.is_alive === false
                          ? "خیر"
                          : ""
                      }
                      onChange={(e) => {
                        formik.setFieldValue(
                          "is_alive",
                          e.target.value === "بلی" ? "بلی" : "خیر"
                        );
                      }}
                      sx={{ justifyContent: "space-around" }}
                    >
                      <FormControlLabel
                        value="بلی"
                        control={<Radio />}
                        label="بلی"
                      />
                      <FormControlLabel
                        value="خیر"
                        control={<Radio />}
                        label="خیر"
                      />
                    </RadioGroup>
                  </FormControl>
                </LabelField>
              ) : (
                <InfoBox
                  icon={FavoriteIcon}
                  label="در قید حیات"
                  value={getAliveStatusDisplay(formik.values.is_alive)}
                />
              )}
            </Grid>
          </Grid>
          <Grid
            container
            xs={12}
            md={6}
            gap={SPACING.TINY}
            px={SPACING.TINY}
            mt={{ xs: 1, md: 0 }}
          >
            <Grid item xs={12}>
              {isAdmin ? (
                <DatePicker
                  label="تاریخ تولد"
                  value={
                    formik.values.birth_date
                      ? moment(
                          convertPersianToGregorian(formik.values.birth_date)
                        )
                      : null
                  }
                  onChange={(newValue) => {
                    if (newValue) {
                      const gregorianDate =
                        moment(newValue).format("YYYY-MM-DD");
                      const persianDate =
                        convertGregorianToPersian(gregorianDate);
                      formik.setFieldValue("birth_date", persianDate);
                    } else {
                      formik.setFieldValue("birth_date", "");
                    }
                  }}
                  renderInput={(params) => (
                    <TextField {...params} fullWidth variant="outlined" />
                  )}
                />
              ) : (
                <InfoBox
                  icon={CakeIcon}
                  label="تاریخ تولد"
                  value={getBirthDateDisplay()}
                />
              )}
            </Grid>
            <Grid item xs={12}>
              {isAdmin ? (
                <TextField
                  label="نام پدر"
                  variant="outlined"
                  fullWidth
                  id="father_name"
                  name="father_name"
                  value={formik.values.father_name}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                />
              ) : (
                <InfoBox
                  icon={PersonIcon}
                  label="نام پدر"
                  value={formik.values.father_name}
                />
              )}
            </Grid>
            <Grid item xs={12}>
              {isAdmin ? (
                <LabelField label="جنسیت">
                  <FormControl fullWidth>
                    <RadioGroup
                      row
                      name="gender"
                      value={
                        formik.values.gender === "True" ||
                        formik.values.gender === true
                          ? "True"
                          : formik.values.gender === "False" ||
                            formik.values.gender === false
                          ? "False"
                          : ""
                      }
                      onChange={(e) => {
                        formik.setFieldValue("gender", e.target.value);
                      }}
                      sx={{ justifyContent: "space-around" }}
                    >
                      <FormControlLabel
                        value="True"
                        control={<Radio />}
                        label="مرد"
                      />
                      <FormControlLabel
                        value="False"
                        control={<Radio />}
                        label="زن"
                      />
                    </RadioGroup>
                  </FormControl>
                </LabelField>
              ) : (
                <InfoBox
                  icon={FaceIcon}
                  label="جنسیت"
                  value={getGenderDisplay(formik.values.gender)}
                />
              )}
            </Grid>
            <Grid item xs={12}>
              {isAdmin ? (
                <Autocomplete
                  size="small"
                  style={{ width: "100%" }}
                  disablePortal
                  id="city"
                  options={
                    cities
                      ? cities.map((i) => ({
                          id: i.key ?? i.id,
                          label: i.name,
                        }))
                      : []
                  }
                  value={(() => {
                    const c = cities.find(
                      (c) => (c.key ?? c.id) === formik.values.city
                    );
                    if (c)
                      return {
                        id: c.key ?? c.id,
                        label: c.name,
                      };
                    if (formik.values.person_city)
                      return {
                        id: null,
                        label: formik.values.person_city,
                      };
                    return null;
                  })()}
                  isOptionEqualToValue={(a, b) => a?.id === b?.id}
                  onChange={(e, value) => {
                    formik.setFieldValue("city", value ? value.id : "");
                    formik.setFieldValue(
                      "person_city",
                      value ? value.label : ""
                    );
                  }}
                  renderInput={(params) => (
                    <TextField {...params} label="شهر" />
                  )}
                />
              ) : (
                <InfoBox
                  icon={LocationCityIcon}
                  label="شهر"
                  value={
                    cities.find((c) => (c.key ?? c.id) === formik.values.city)
                      ?.name ||
                    formik.values.person_city ||
                    "-"
                  }
                />
              )}
            </Grid>
            <Grid item xs={12} mt={{ xs: 1, md: 0 }}>
              {!guild &&
              hasInquiry &&
              !isAdmin &&
              !isSuperAdmin &&
              !isKillHouse ? (
                <InfoBox
                  icon={PhoneIcon}
                  label="شماره همراه"
                  value={formik.values.mobile}
                />
              ) : isKillHouse &&
                formik.values.mobile &&
                /^[0-9]{11}$/.test(formik.values.mobile) ? (
                <InfoBox
                  icon={PhoneIcon}
                  label="شماره همراه"
                  value={formik.values.mobile}
                />
              ) : (
                <TextField
                  label="شماره همراه"
                  variant="outlined"
                  fullWidth
                  required
                  id="mobile"
                  name="mobile"
                  value={formik.values.mobile}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  error={
                    Boolean(formik.errors.mobile) &&
                    (formik.touched.mobile || formik.submitCount > 0)
                  }
                  helperText={
                    (formik.touched.mobile || formik.submitCount > 0) &&
                    formik.errors.mobile
                  }
                  disabled={
                    isKillHouse &&
                    formik.values.mobile &&
                    /^[0-9]{11}$/.test(formik.values.mobile)
                  }
                />
              )}
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
};
