'use client'

import { useActionState } from 'react'
import Link from 'next/link'
import { Logo } from '@/components/terrano/Logo'
import { Icon } from '@/components/terrano/Icon'

type FormState = { error?: string }
type Action = (prev: FormState, fd: FormData) => Promise<FormState>

export function AuthForm({
  mode,
  action,
  next,
}: {
  mode: 'login' | 'register'
  action: Action
  next?: string
}) {
  const [state, formAction, pending] = useActionState(action, {})
  const isRegister = mode === 'register'

  return (
    <div className="auth-split" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', minHeight: 'calc(100vh - 64px)' }}>
      {/* Panel formulario */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '48px 28px' }}>
        <div style={{ width: '100%', maxWidth: 380 }}>
          <Link href="/"><Logo size={15} /></Link>
          <h1 className="display" style={{ fontSize: 34, fontWeight: 600, letterSpacing: '-0.02em', marginTop: 28 }}>
            {isRegister ? 'Crea tu cuenta' : 'Inicia sesión'}
          </h1>
          <p style={{ marginTop: 6, fontSize: 14, color: 'var(--muted)' }}>
            {isRegister ? 'Para publicar y gestionar activos en Portal Minería.' : 'Accede a tu panel de Portal Minería.'}
          </p>

          <form action={formAction} style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 14 }}>
            {next && <input type="hidden" name="next" value={next} />}
            {isRegister && (
              <>
                <Input name="name" label="Nombre" required />
                <Input name="company" label="Empresa (opcional)" />
              </>
            )}
            <Input name="email" type="email" label="Email" required />
            <Input name="password" type="password" label="Contraseña" required />
            {state.error && (
              <p className="mono" style={{ fontSize: 12, color: 'var(--warn, #c2410c)' }}>{state.error}</p>
            )}
            <button type="submit" disabled={pending} className="btn accent" style={{ marginTop: 4, height: 42 }}>
              {pending ? 'Procesando…' : isRegister ? 'Crear cuenta' : 'Entrar'}
              {!pending && <Icon name="arrow-right" size={12} />}
            </button>
          </form>

          <p style={{ marginTop: 24, fontSize: 13, color: 'var(--muted)' }}>
            {isRegister ? (
              <>
                ¿Ya tienes cuenta?{' '}
                <Link href="/login" style={{ color: 'var(--accent)', fontWeight: 600 }}>Inicia sesión</Link>
              </>
            ) : (
              <>
                ¿No tienes cuenta?{' '}
                <Link href="/registro" style={{ color: 'var(--accent)', fontWeight: 600 }}>Regístrate</Link>
              </>
            )}
          </p>
        </div>
      </div>

      {/* Panel imagen */}
      <div
        className="auth-aside"
        style={{
          position: 'relative',
          background: "linear-gradient(135deg, rgba(20,49,74,0.86), rgba(15,12,8,0.72)), url('/listings/open-pit.jpg')",
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          color: '#f5f1e8',
          padding: 48,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'flex-end',
        }}
      >
        <div className="mono uppercase-wide" style={{ fontSize: 11, letterSpacing: '0.18em', opacity: 0.8 }}>
          <span style={{ color: 'var(--accent-2)' }}>▣</span> Portal Minería
        </div>
        <div className="display" style={{ fontSize: 'clamp(28px, 3vw, 40px)', fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1.05, marginTop: 12, maxWidth: 420 }}>
          El suelo latinoamericano, listado y transable.
        </div>
        <p style={{ marginTop: 14, fontSize: 14, opacity: 0.85, maxWidth: 380 }}>
          Publica concesiones, propiedades, plantas y relaves. Conecta con compradores, inversionistas y
          operadores verificados.
        </p>
      </div>
    </div>
  )
}

function Input({
  name,
  label,
  type = 'text',
  required = false,
}: {
  name: string
  label: string
  type?: string
  required?: boolean
}) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column' }}>
      <span className="mono uppercase-wide" style={{ fontSize: 10, color: 'var(--muted)', letterSpacing: '0.08em', marginBottom: 6 }}>{label}</span>
      <input name={name} type={type} required={required} className="input" style={{ height: 42 }} />
    </label>
  )
}
