import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { api } from '../api/client'

type FormData = {
  company_name: string
  first_name: string
  last_name: string
  email: string
  password: string
  password_confirm: string
}

const INITIAL: FormData = {
  company_name: '', first_name: '', last_name: '',
  email: '', password: '', password_confirm: '',
}

const STEPS = ['Unternehmen', 'Persönliche Daten', 'Passwort']

export function RegisterPage() {
  const navigate = useNavigate()
  const [step, setStep]       = useState(1)
  const [form, setForm]       = useState<FormData>(INITIAL)
  const [error, setError]     = useState('')
  const [loading, setLoading] = useState(false)

  const update = (field: keyof FormData) =>
    (e: React.ChangeEvent<HTMLInputElement>) =>
      setForm(f => ({ ...f, [field]: e.target.value }))

  function validate(): string {
    if (step === 1 && form.company_name.trim().length < 2)
      return 'Unternehmensname muss mindestens 2 Zeichen haben.'
    if (step === 2) {
      if (!form.first_name.trim()) return 'Vorname ist erforderlich.'
      if (!form.last_name.trim())  return 'Nachname ist erforderlich.'
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email))
        return 'Bitte eine gültige E-Mail-Adresse eingeben.'
    }
    if (step === 3) {
      if (form.password.length < 8)
        return 'Passwort muss mindestens 8 Zeichen haben.'
      if (!/[A-Z]/.test(form.password))
        return 'Passwort muss mindestens einen Großbuchstaben enthalten.'
      if (!/\d/.test(form.password))
        return 'Passwort muss mindestens eine Ziffer enthalten.'
      if (form.password !== form.password_confirm)
        return 'Passwörter stimmen nicht überein.'
    }
    return ''
  }

  async function handleNext() {
    const err = validate()
    if (err) { setError(err); return }
    setError('')

    if (step < 3) { setStep(s => s + 1); return }

    setLoading(true)
    try {
      const data = await api.post<{ access_token: string; refresh_token: string }>(
        '/auth/register',
        {
          company_name: form.company_name,
          first_name:   form.first_name,
          last_name:    form.last_name,
          email:        form.email,
          password:     form.password,
        },
      )
      localStorage.setItem('access_token',  data.access_token)
      localStorage.setItem('refresh_token', data.refresh_token)
      navigate('/dashboard')
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Unbekannter Fehler')
    } finally {
      setLoading(false)
    }
  }

  function handleKeyDown(e: React.KeyboardEvent) {
    if (e.key === 'Enter') handleNext()
  }

  const inputClass =
    'mt-1 w-full border border-gray-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent'

  return (
    <div className='min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4'>
      <div className='w-full max-w-md bg-white rounded-2xl shadow-lg p-8'>

        {/* Logo / Title */}
        <div className='mb-6'>
          <div className='flex items-center gap-2 mb-1'>
            <div className='w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center'>
              <span className='text-white font-bold text-sm'>TM</span>
            </div>
            <span className='text-lg font-bold text-gray-800'>TimeMaster</span>
          </div>
          <h1 className='text-xl font-semibold text-gray-800 mt-3'>Konto erstellen</h1>
          <p className='text-sm text-gray-500'>Schritt {step} von {STEPS.length}</p>
        </div>

        {/* Fortschrittsbalken */}
        <div className='flex gap-1.5 mb-6'>
          {STEPS.map((label, i) => (
            <div key={label} className='flex-1'>
              <div className={`h-1 rounded-full transition-colors ${
                i + 1 <= step ? 'bg-blue-500' : 'bg-gray-200'
              }`} />
              <p className={`text-xs mt-1 font-medium ${
                i + 1 <= step ? 'text-blue-600' : 'text-gray-400'
              }`}>{label}</p>
            </div>
          ))}
        </div>

        {/* Schritt 1: Unternehmen */}
        {step === 1 && (
          <div className='space-y-4' onKeyDown={handleKeyDown}>
            <label className='block'>
              <span className='text-sm font-medium text-gray-700'>Unternehmensname *</span>
              <input
                value={form.company_name}
                onChange={update('company_name')}
                className={inputClass}
                placeholder='Muster GmbH'
                autoFocus
              />
            </label>
            <p className='text-xs text-gray-400'>
              Der Name deines Unternehmens, wie er für Mitarbeiter angezeigt wird.
            </p>
          </div>
        )}

        {/* Schritt 2: Persönliche Daten */}
        {step === 2 && (
          <div className='space-y-4' onKeyDown={handleKeyDown}>
            <div className='flex gap-3'>
              <label className='block flex-1'>
                <span className='text-sm font-medium text-gray-700'>Vorname *</span>
                <input
                  value={form.first_name}
                  onChange={update('first_name')}
                  className={inputClass}
                  placeholder='Max'
                  autoFocus
                />
              </label>
              <label className='block flex-1'>
                <span className='text-sm font-medium text-gray-700'>Nachname *</span>
                <input
                  value={form.last_name}
                  onChange={update('last_name')}
                  className={inputClass}
                  placeholder='Mustermann'
                />
              </label>
            </div>
            <label className='block'>
              <span className='text-sm font-medium text-gray-700'>E-Mail-Adresse *</span>
              <input
                type='email'
                value={form.email}
                onChange={update('email')}
                className={inputClass}
                placeholder='max@muster-gmbh.de'
              />
            </label>
            <p className='text-xs text-gray-400'>
              Du wirst Administrator deines Unternehmens.
            </p>
          </div>
        )}

        {/* Schritt 3: Passwort */}
        {step === 3 && (
          <div className='space-y-4' onKeyDown={handleKeyDown}>
            <label className='block'>
              <span className='text-sm font-medium text-gray-700'>Passwort *</span>
              <input
                type='password'
                value={form.password}
                onChange={update('password')}
                className={inputClass}
                placeholder='Mindestens 8 Zeichen'
                autoFocus
              />
            </label>
            <label className='block'>
              <span className='text-sm font-medium text-gray-700'>Passwort bestätigen *</span>
              <input
                type='password'
                value={form.password_confirm}
                onChange={update('password_confirm')}
                className={inputClass}
                placeholder='Passwort wiederholen'
              />
            </label>
            <ul className='text-xs text-gray-400 space-y-1'>
              <li className={form.password.length >= 8 ? 'text-green-600' : ''}>
                {form.password.length >= 8 ? '✓' : '·'} Mindestens 8 Zeichen
              </li>
              <li className={/[A-Z]/.test(form.password) ? 'text-green-600' : ''}>
                {/[A-Z]/.test(form.password) ? '✓' : '·'} Mindestens ein Großbuchstabe
              </li>
              <li className={/\d/.test(form.password) ? 'text-green-600' : ''}>
                {/\d/.test(form.password) ? '✓' : '·'} Mindestens eine Ziffer
              </li>
            </ul>
          </div>
        )}

        {/* Fehler */}
        {error && (
          <div className='mt-4 text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg px-3 py-2.5'>
            {error}
          </div>
        )}

        {/* Buttons */}
        <div className='flex justify-between items-center mt-6'>
          {step > 1 ? (
            <button
              onClick={() => { setError(''); setStep(s => s - 1) }}
              className='px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors'
            >
              Zurück
            </button>
          ) : (
            <span />
          )}
          <button
            onClick={handleNext}
            disabled={loading}
            className='px-6 py-2 text-sm font-semibold text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors'
          >
            {loading ? 'Wird erstellt…' : step < 3 ? 'Weiter →' : 'Konto erstellen'}
          </button>
        </div>

        <p className='text-center text-sm text-gray-500 mt-6'>
          Bereits ein Konto?{' '}
          <Link to='/login' className='text-blue-600 hover:underline font-medium'>
            Anmelden
          </Link>
        </p>
      </div>
    </div>
  )
}
