// ProfileSettings.jsx — User profile and password management

const PROFESSIONAL_SPECIALTIES = ['Medicina General','Odontología','Kinesiología','Psicología','Nutrición','Fonoaudiología','Dermatología'];
const OWNER_SPECIALTIES        = ['Dental','Kinesiología','Psicología','Medicina General','Dermatología','Nutrición'];

const ROLE_LABELS = {
  professional:  'Profesional',
  owner:         'Propietario',
  admin:         'Administrador',
  admin_limited: 'Admin (limitado)',
};

const ProfileSettings = ({ onBack, userRole = 'professional' }) => {
  const [user, setUser] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const [successMsg, setSuccessMsg] = React.useState('');
  const [activeTab, setActiveTab] = React.useState('profile'); // profile | password

  // Form state for profile
  const [profile, setProfile] = React.useState({
    fullName:    '',
    email:       '',
    phone:       '',
    specialty:   '',
    role:        '',
    companyName: '',
    address:     '',
  });

  // "Otro" specialty custom input
  const [customSpecialty, setCustomSpecialty] = React.useState('');

  // Form state for password
  const [password, setPassword] = React.useState({ current: '', new: '', confirm: '' });
  const [showPasswords, setShowPasswords] = React.useState({ current: false, new: false, confirm: false });

  // ── Helpers ────────────────────────────────────────────────────────────────
  const effectiveRole = profile.role || userRole;

  const specialtyList = effectiveRole === 'owner' ? OWNER_SPECIALTIES : PROFESSIONAL_SPECIALTIES;

  // A specialty is "custom" when it's non-empty AND not in the predefined list
  const isCustomSpecialty = profile.specialty !== '' && !specialtyList.includes(profile.specialty);

  // ── Load on mount ──────────────────────────────────────────────────────────
  React.useEffect(() => {
    // Pre-fill immediately from localStorage
    const userJson = localStorage.getItem('lokat_user');
    if (userJson) {
      const ud = JSON.parse(userJson);
      setUser(ud);
      const sp = ud.specialty || '';
      const list = (ud.role === 'owner' ? OWNER_SPECIALTIES : PROFESSIONAL_SPECIALTIES);
      if (sp && !list.includes(sp)) setCustomSpecialty(sp);
      setProfile({
        fullName:    ud.fullName    || '',
        email:       ud.email       || '',
        phone:       ud.phone       || '',
        specialty:   sp,
        role:        ud.role        || '',
        companyName: ud.companyName || '',
        address:     ud.address     || '',
      });
    }

    // Refresh from backend
    fetchWithAuth('https://lokat.fly.dev/api/users/profile', {})
      .then(res => res.json())
      .then(data => {
        if (data?.user) {
          setUser(data.user);
          const sp   = data.user.specialty || '';
          const list = (data.user.role === 'owner' ? OWNER_SPECIALTIES : PROFESSIONAL_SPECIALTIES);
          if (sp && !list.includes(sp)) setCustomSpecialty(sp);
          setProfile({
            fullName:    data.user.fullName    || '',
            email:       data.user.email       || '',
            phone:       data.user.phone       || '',
            specialty:   sp,
            role:        data.user.role        || '',
            companyName: data.user.companyName || '',
            address:     data.user.address     || '',
          });
        }
      })
      .catch(() => { /* silently ignore — localStorage values already shown */ });
  }, []);

  const set = (field, value) => {
    setProfile(p => ({...p, [field]: value}));
    setErrors(e => ({...e, [field]: undefined}));
  };

  const handlePasswordChange = (field, value) => {
    setPassword(p => ({...p, [field]: value}));
    setErrors(e => ({...e, [field]: undefined}));
  };

  // ── Validation ─────────────────────────────────────────────────────────────
  const validateProfile = () => {
    const e = {};
    if (!profile.fullName.trim()) e.fullName = 'Requerido';
    if (!profile.phone.trim())    e.phone    = 'Requerido';
    if (effectiveRole === 'owner' && !profile.companyName.trim()) e.companyName = 'Requerido';
    return e;
  };

  const validatePassword = () => {
    const e = {};
    if (!password.current)                            e.current = 'Requerido';
    if (!password.new)                                e.new     = 'Requerido';
    if (!password.confirm)                            e.confirm = 'Requerido';
    if (password.new && password.new.length < 6)      e.new     = 'Mínimo 6 caracteres';
    if (password.new !== password.confirm)            e.confirm = 'Las contraseñas no coinciden';
    return e;
  };

  // ── Save profile ───────────────────────────────────────────────────────────
  const handleSaveProfile = async () => {
    const e = validateProfile();
    if (Object.keys(e).length) { setErrors(e); return; }

    setLoading(true);
    setSuccessMsg('');
    setErrors({});

    try {
      const payload = {
        fullName:  profile.fullName,
        phone:     profile.phone,
        specialty: profile.specialty || null,
      };
      if (effectiveRole === 'owner') {
        payload.companyName = profile.companyName;
        payload.address     = profile.address;
      }

      const response = await fetchWithAuth('https://lokat.fly.dev/api/users/profile', {
        method:  'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify(payload),
      });

      const data = await response.json();

      if (!response.ok) {
        setErrors({ submit: data.error || 'Error al guardar' });
        setLoading(false);
        return;
      }

      // Update localStorage
      const updatedUser = {
        ...user,
        fullName:    data.user.fullName,
        phone:       data.user.phone,
        specialty:   data.user.specialty,
        companyName: data.user.companyName,
        address:     data.user.address,
      };
      localStorage.setItem('lokat_user', JSON.stringify(updatedUser));
      setUser(updatedUser);
      setSuccessMsg('✅ Perfil actualizado exitosamente');
      setLoading(false);
    } catch (err) {
      if (err.sessionExpired) return;
      setErrors({ submit: 'Error de conexión. Intenta de nuevo.' });
      setLoading(false);
    }
  };

  // ── Change password ────────────────────────────────────────────────────────
  const handleChangePassword = async () => {
    const e = validatePassword();
    if (Object.keys(e).length) { setErrors(e); return; }

    setLoading(true);
    setSuccessMsg('');
    setErrors({});

    try {
      const response = await fetchWithAuth('https://lokat.fly.dev/api/users/change-password', {
        method:  'POST',
        headers: { 'Content-Type': 'application/json' },
        body:    JSON.stringify({ currentPassword: password.current, newPassword: password.new }),
      });

      const data = await response.json();

      if (!response.ok) {
        setErrors({ submit: data.error || 'Error al cambiar contraseña' });
        setLoading(false);
        return;
      }

      setSuccessMsg('✅ Contraseña cambiada exitosamente');
      setPassword({ current: '', new: '', confirm: '' });
      setLoading(false);
    } catch (err) {
      if (err.sessionExpired) return;
      setErrors({ submit: 'Error de conexión. Intenta de nuevo.' });
      setLoading(false);
    }
  };

  // ── Styles ─────────────────────────────────────────────────────────────────
  const styles = {
    page:           { minHeight: '100vh', background: '#f8f9fa', paddingBottom: 40 },
    header:         { background: '#0984e3', color: '#fff', padding: '0 16px', height: 60, display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'sticky', top: 0, zIndex: 50 },
    headerLeft:     { display: 'flex', alignItems: 'center', gap: 8 },
    backBtn:        { background: 'rgba(255,255,255,0.15)', border: 'none', color: '#fff', padding: '6px 10px', borderRadius: 6, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', justifyContent: 'center', lineHeight: 1 },
    headerTitle:    { fontSize: 14, fontWeight: 700, letterSpacing: 0.5 },
    container:      { maxWidth: 520, margin: '0 auto', padding: '20px 16px' },
    tabs:           { display: 'flex', gap: 12, marginBottom: 24, borderBottom: '1px solid #e9ecef' },
    tabBtn:         { flex: 1, padding: '14px 16px', border: 'none', background: 'none', fontSize: 14, fontWeight: 600, cursor: 'pointer', color: '#adb5bd', borderBottom: '3px solid transparent', transition: 'all 0.3s' },
    tabBtnActive:   { color: '#0984e3', borderBottomColor: '#0984e3' },
    section:        { background: '#fff', borderRadius: 12, padding: 20, border: '1px solid #e9ecef', marginBottom: 16 },
    sectionTitle:   { fontSize: 16, fontWeight: 700, marginBottom: 18, color: '#2d3436' },
    formGroup:      { marginBottom: 16 },
    label:          { display: 'block', fontSize: 13, fontWeight: 600, marginBottom: 6, color: '#2d3436' },
    input:          { width: '100%', padding: '12px 14px', border: '1px solid #e9ecef', borderRadius: 8, fontSize: 14, fontFamily: 'inherit', boxSizing: 'border-box', transition: 'border 0.3s' },
    inputReadOnly:  { width: '100%', padding: '12px 14px', border: '1px solid #e9ecef', borderRadius: 8, fontSize: 14, fontFamily: 'inherit', boxSizing: 'border-box', background: '#f8f9fa', color: '#636e72', cursor: 'default' },
    inputError:     { borderColor: '#e74c3c' },
    inputWrapper:   { position: 'relative' },
    eyeBtn:         { position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', padding: 4, display: 'flex', alignItems: 'center', justifyContent: 'center' },
    fieldError:     { display: 'block', fontSize: 12, color: '#e74c3c', marginTop: 4 },
    fieldHint:      { display: 'block', fontSize: 12, color: '#adb5bd', marginTop: 4 },
    submitError:    { display: 'block', fontSize: 13, color: '#e74c3c', background: '#fadbd8', padding: 12, borderRadius: 8, marginBottom: 16 },
    successMsg:     { display: 'block', fontSize: 13, color: '#27ae60', background: '#d5f4e6', padding: 12, borderRadius: 8, marginBottom: 16 },
    roleBadge:      { display: 'inline-block', padding: '4px 12px', borderRadius: 20, fontSize: 12, fontWeight: 700, background: '#e3f0fc', color: '#0984e3', letterSpacing: 0.3 },
    btnPrimary:     { width: '100%', padding: 14, background: '#0984e3', color: '#fff', border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', transition: 'background 0.3s' },
    btnPrimaryHover:{ background: '#0966c2' },
    spinner:        { display: 'inline-block', width: 14, height: 14, border: '2px solid rgba(255,255,255,0.3)', borderTop: '2px solid #fff', borderRadius: '50%', animation: 'spin 0.6s linear infinite', marginRight: 8 },
  };

  // ── Render ─────────────────────────────────────────────────────────────────
  return (
    <div style={styles.page}>
      {/* Header */}
      <div style={styles.header}>
        <div style={styles.headerLeft}>
          <button style={styles.backBtn} onClick={onBack}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>
          </button>
          <div style={styles.headerTitle}>CONFIGURACIÓN</div>
        </div>
      </div>

      <div style={styles.container}>
        {/* Tabs */}
        <div style={styles.tabs}>
          <button
            style={{...styles.tabBtn, ...(activeTab === 'profile' ? styles.tabBtnActive : {})}}
            onClick={() => { setActiveTab('profile'); setErrors({}); setSuccessMsg(''); }}
          >
            Perfil
          </button>
          <button
            style={{...styles.tabBtn, ...(activeTab === 'password' ? styles.tabBtnActive : {})}}
            onClick={() => { setActiveTab('password'); setErrors({}); setSuccessMsg(''); }}
          >
            Contraseña
          </button>
        </div>

        {/* ── Profile Tab ── */}
        {activeTab === 'profile' && (
          <>
            {errors.submit && <div style={styles.submitError}>{errors.submit}</div>}
            {successMsg    && <div style={styles.successMsg}>{successMsg}</div>}

            <div style={styles.section}>
              <div style={styles.sectionTitle}>Información Personal</div>

              {/* Role — read-only badge */}
              <div style={styles.formGroup}>
                <label style={styles.label}>Tipo de cuenta</label>
                <div>
                  <span style={styles.roleBadge}>
                    {ROLE_LABELS[effectiveRole] || effectiveRole || '—'}
                  </span>
                </div>
              </div>

              {/* Email — read-only */}
              <div style={styles.formGroup}>
                <label style={styles.label}>Email</label>
                <input
                  style={styles.inputReadOnly}
                  type="email"
                  value={profile.email}
                  readOnly
                />
                <span style={styles.fieldHint}>El email no se puede cambiar desde aquí.</span>
              </div>

              {/* Full name */}
              <div style={styles.formGroup}>
                <label style={styles.label}>Nombre completo</label>
                <input
                  style={{...styles.input, ...(errors.fullName ? styles.inputError : {})}}
                  type="text"
                  placeholder="Tu nombre"
                  value={profile.fullName}
                  onChange={e => set('fullName', e.target.value)}
                />
                {errors.fullName && <span style={styles.fieldError}>{errors.fullName}</span>}
              </div>

              {/* Phone */}
              <div style={styles.formGroup}>
                <label style={styles.label}>Teléfono</label>
                <input
                  style={{...styles.input, ...(errors.phone ? styles.inputError : {})}}
                  type="tel"
                  placeholder="+56 9 1234 5678"
                  value={profile.phone}
                  onChange={e => set('phone', e.target.value)}
                />
                {errors.phone && <span style={styles.fieldError}>{errors.phone}</span>}
              </div>

              {/* Specialty — for both roles */}
              <div style={styles.formGroup}>
                <label style={styles.label}>
                  Especialidad&nbsp;
                  <span style={{color:'#adb5bd', fontWeight:400}}>(opcional)</span>
                </label>
                <select
                  style={styles.input}
                  value={isCustomSpecialty ? 'otro' : profile.specialty}
                  onChange={e => {
                    if (e.target.value === 'otro') {
                      setCustomSpecialty('');
                      set('specialty', 'otro');
                    } else {
                      setCustomSpecialty('');
                      set('specialty', e.target.value);
                    }
                  }}
                >
                  <option value="">Seleccionar especialidad</option>
                  {specialtyList.map(s => <option key={s} value={s}>{s}</option>)}
                  <option value="otro">Otro</option>
                </select>
                {isCustomSpecialty && (
                  <input
                    style={{...styles.input, marginTop: 8}}
                    placeholder="Escribe tu especialidad"
                    value={customSpecialty}
                    onChange={e => {
                      setCustomSpecialty(e.target.value);
                      set('specialty', e.target.value);
                    }}
                  />
                )}
              </div>

              {/* Owner-only fields */}
              {effectiveRole === 'owner' && (
                <>
                  <div style={styles.formGroup}>
                    <label style={styles.label}>Nombre de empresa/clínica</label>
                    <input
                      style={{...styles.input, ...(errors.companyName ? styles.inputError : {})}}
                      type="text"
                      placeholder="Tu empresa"
                      value={profile.companyName}
                      onChange={e => set('companyName', e.target.value)}
                    />
                    {errors.companyName && <span style={styles.fieldError}>{errors.companyName}</span>}
                  </div>

                  <div style={styles.formGroup}>
                    <label style={styles.label}>Dirección <span style={{color:'#adb5bd', fontWeight:400}}>(opcional)</span></label>
                    <input
                      style={styles.input}
                      type="text"
                      placeholder="Calle Principal 123"
                      value={profile.address}
                      onChange={e => set('address', e.target.value)}
                    />
                  </div>
                </>
              )}

              <button
                style={styles.btnPrimary}
                onClick={handleSaveProfile}
                disabled={loading}
                onMouseEnter={e => !loading && (e.target.style.background = styles.btnPrimaryHover.background)}
                onMouseLeave={e => !loading && (e.target.style.background = styles.btnPrimary.background)}
              >
                {loading
                  ? <span style={{display:'flex', alignItems:'center', justifyContent:'center'}}><span style={styles.spinner}></span>Guardando...</span>
                  : 'Guardar cambios'}
              </button>
            </div>
          </>
        )}

        {/* ── Password Tab ── */}
        {activeTab === 'password' && (
          <>
            {errors.submit && <div style={styles.submitError}>{errors.submit}</div>}
            {successMsg    && <div style={styles.successMsg}>{successMsg}</div>}

            <div style={styles.section}>
              <div style={styles.sectionTitle}>Cambiar contraseña</div>

              {[
                { key: 'current', label: 'Contraseña actual',         placeholder: 'Ingresa tu contraseña actual' },
                { key: 'new',     label: 'Nueva contraseña',          placeholder: 'Mínimo 6 caracteres' },
                { key: 'confirm', label: 'Confirmar nueva contraseña', placeholder: 'Confirma tu nueva contraseña' },
              ].map(({ key, label, placeholder }) => (
                <div key={key} style={styles.formGroup}>
                  <label style={styles.label}>{label}</label>
                  <div style={styles.inputWrapper}>
                    <input
                      style={{...styles.input, ...(errors[key] ? styles.inputError : {}), paddingRight: 44}}
                      type={showPasswords[key] ? 'text' : 'password'}
                      placeholder={placeholder}
                      value={password[key]}
                      onChange={e => handlePasswordChange(key, e.target.value)}
                    />
                    <button
                      style={styles.eyeBtn}
                      onClick={() => setShowPasswords(p => ({...p, [key]: !p[key]}))}
                    >
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#adb5bd" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                    </button>
                  </div>
                  {errors[key] && <span style={styles.fieldError}>{errors[key]}</span>}
                </div>
              ))}

              <button
                style={styles.btnPrimary}
                onClick={handleChangePassword}
                disabled={loading}
                onMouseEnter={e => !loading && (e.target.style.background = styles.btnPrimaryHover.background)}
                onMouseLeave={e => !loading && (e.target.style.background = styles.btnPrimaryHover.background)}
              >
                {loading
                  ? <span style={{display:'flex', alignItems:'center', justifyContent:'center'}}><span style={styles.spinner}></span>Cambiando...</span>
                  : 'Cambiar contraseña'}
              </button>
            </div>
          </>
        )}
      </div>

      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
};

window.ProfileSettings = ProfileSettings;
