import { useState } from 'react'
import { auth, db } from '../firebase'
import { createUserWithEmailAndPassword, signInWithEmailAndPassword } from 'firebase/auth'
import { doc, setDoc, getDoc } from 'firebase/firestore'

const COLONIAS = [
  'Zona Centro',
  'Las Arboledas',
  'Trojes',
  'San Juanico',
  'Los Olivos',
  'Rancho Seco',
  'Las Insurgentes',
]

export default function Login({ onLogin }) {
  const [modo,     setModo]     = useState('login')   // 'login' | 'registro'
  const [email,    setEmail]    = useState('')
  const [password, setPassword] = useState('')
  const [colonia,  setColonia]  = useState(COLONIAS[0])
  const [loading,  setLoading]  = useState(false)
  const [error,    setError]    = useState('')

  async function handleLogin() {
    setLoading(true)
    setError('')
    try {
      const cred = await signInWithEmailAndPassword(auth, email, password)
      // Leer la colonia guardada en Firestore
      const snap = await getDoc(doc(db, 'usuarios', cred.user.uid))
      const coloniaGuardada = snap.exists() ? snap.data().colonia : COLONIAS[0]
      onLogin({ uid: cred.user.uid, email: cred.user.email, colonia: coloniaGuardada })
    } catch (e) {
      setError('Correo o contraseña incorrectos')
    } finally {
      setLoading(false)
    }
  }

  async function handleRegistro() {
    setLoading(true)
    setError('')
    try {
      const cred = await createUserWithEmailAndPassword(auth, email, password)
      // Guardar colonia del usuario en Firestore
      await setDoc(doc(db, 'usuarios', cred.user.uid), {
        email:    cred.user.email,
        colonia,
        creadoEn: new Date().toISOString(),
      })
      onLogin({ uid: cred.user.uid, email: cred.user.email, colonia })
    } catch (e) {
      if (e.code === 'auth/email-already-in-use') setError('Este correo ya está registrado')
      else if (e.code === 'auth/weak-password')   setError('La contraseña debe tener al menos 6 caracteres')
      else setError('Error al crear cuenta')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={styles.page}>
      <div style={styles.card}>
        {/* Logo */}
        <div style={styles.logo}>🚛</div>
        <div style={styles.title}>EcoTrack Celaya</div>
        <div style={styles.subtitle}>Sistema de Notificación de Recolección</div>

        {/* Tabs login / registro */}
        <div style={styles.tabs}>
          <div
            onClick={() => { setModo('login'); setError('') }}
            style={{ ...styles.tab, ...(modo === 'login' ? styles.tabActive : {}) }}
          >
            Iniciar sesión
          </div>
          <div
            onClick={() => { setModo('registro'); setError('') }}
            style={{ ...styles.tab, ...(modo === 'registro' ? styles.tabActive : {}) }}
          >
            Registrarse
          </div>
        </div>

        {/* Campos */}
        <div style={styles.group}>
          <label style={styles.label}>Correo electrónico</label>
          <input
            type="email"
            placeholder="tucorreo@gmail.com"
            value={email}
            onChange={e => setEmail(e.target.value)}
            style={styles.input}
          />
        </div>

        <div style={styles.group}>
          <label style={styles.label}>Contraseña</label>
          <input
            type="password"
            placeholder="Mínimo 6 caracteres"
            value={password}
            onChange={e => setPassword(e.target.value)}
            style={styles.input}
          />
        </div>

        {/* Colonia — solo en registro */}
        {modo === 'registro' && (
          <div style={styles.group}>
            <label style={styles.label}>Tu colonia</label>
            <select
              value={colonia}
              onChange={e => setColonia(e.target.value)}
              style={styles.select}
            >
              {COLONIAS.map(c => (
                <option key={c} value={c}>{c}</option>
              ))}
            </select>
            <div style={styles.hint}>
              Selecciona la colonia donde vives para recibir el ETA correcto
            </div>
          </div>
        )}

        {/* Error */}
        {error && <div style={styles.error}>{error}</div>}

        {/* Botón principal */}
        <button
          onClick={modo === 'login' ? handleLogin : handleRegistro}
          disabled={loading || !email || !password}
          style={{
            ...styles.btn,
            opacity: (loading || !email || !password) ? 0.6 : 1,
          }}
        >
          {loading
            ? 'Cargando...'
            : modo === 'login' ? 'Entrar' : 'Crear cuenta'}
        </button>

        <div style={styles.privacidad}>
          🔒 Tus datos son privados y solo se usan para calcular el ETA de tu colonia
        </div>
      </div>
    </div>
  )
}

const styles = {
  page:       { minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, background: '#0a0e14' },
  card:       { width: '100%', maxWidth: 380, background: '#131820', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 20, padding: '32px 24px' },
  logo:       { fontSize: 40, textAlign: 'center', marginBottom: 8 },
  title:      { fontSize: 20, fontWeight: 600, color: '#e8edf5', textAlign: 'center', marginBottom: 4 },
  subtitle:   { fontSize: 12, color: '#6b7f96', textAlign: 'center', marginBottom: 24 },
  tabs:       { display: 'flex', background: '#0a0e14', borderRadius: 10, padding: 4, marginBottom: 24, gap: 4 },
  tab:        { flex: 1, padding: '8px 0', textAlign: 'center', fontSize: 13, fontWeight: 500, color: '#6b7f96', borderRadius: 8, cursor: 'pointer', transition: 'all 0.2s' },
  tabActive:  { background: '#1a2332', color: '#3d9aff' },
  group:      { marginBottom: 14 },
  label:      { fontSize: 11, fontWeight: 500, letterSpacing: '0.05em', textTransform: 'uppercase', color: '#6b7f96', display: 'block', marginBottom: 6 },
  input:      { width: '100%', background: '#1a2332', border: '1px solid rgba(255,255,255,0.14)', borderRadius: 8, color: '#e8edf5', fontFamily: "'DM Sans', sans-serif", fontSize: 14, padding: '11px 14px', outline: 'none' },
  select:     { width: '100%', background: '#1a2332', border: '1px solid rgba(255,255,255,0.14)', borderRadius: 8, color: '#e8edf5', fontFamily: "'DM Sans', sans-serif", fontSize: 14, padding: '11px 14px', outline: 'none', appearance: 'none' },
  hint:       { fontSize: 11, color: '#3d5570', marginTop: 5, lineHeight: 1.4 },
  error:      { background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.2)', borderRadius: 8, padding: '10px 12px', fontSize: 12, color: '#ef4444', marginBottom: 12 },
  btn:        { width: '100%', padding: 14, borderRadius: 10, border: 'none', background: '#3d9aff', color: '#fff', fontFamily: "'DM Sans', sans-serif", fontSize: 15, fontWeight: 600, cursor: 'pointer', marginBottom: 16, transition: 'opacity 0.2s' },
  privacidad: { fontSize: 11, color: '#3d5570', textAlign: 'center', lineHeight: 1.5 },
}
