'use client'

import { useState } from 'react'
import { createAuthClient } from 'better-auth/react'
import { magicLinkClient } from 'better-auth/client/plugins'
const authClient = createAuthClient({
  plugins: [magicLinkClient()],
})

type Mode = 'password' | 'magic'

export default function LoginPage() {
  const [mode, setMode] = useState<Mode>('password')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [sent, setSent] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true)
    setError('')

    if (mode === 'password') {
      const result = await authClient.signIn.email({
        email,
        password,
        callbackURL: '/dashboard',
      })
      setLoading(false)
      if (result.error) {
        setError(result.error.message ?? 'E-Mail oder Passwort falsch.')
      } else {
        window.location.href = '/dashboard'
      }
    } else {
      const result = await authClient.signIn.magicLink({
        email,
        callbackURL: '/dashboard',
      })
      setLoading(false)
      if (result.error) {
        setError(result.error.message ?? 'Ein Fehler ist aufgetreten.')
      } else {
        setSent(true)
      }
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-brand-500 rounded-2xl mb-4">
            <span className="text-white font-bold text-2xl">I</span>
          </div>
          <h1 className="text-2xl font-bold text-gray-900">InnungsApp Admin</h1>
          <p className="text-gray-500 mt-1">Verwaltungsportal für Innungen</p>
        </div>

        <div className="bg-white rounded-2xl shadow-sm border p-8">
          {sent ? (
            <div className="text-center">
              <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <svg className="w-8 h-8 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
              </div>
              <h2 className="text-xl font-semibold text-gray-900 mb-2">E-Mail gesendet!</h2>
              <p className="text-gray-500">
                Wir haben einen Login-Link an <strong>{email}</strong> gesendet.
                Bitte überprüfen Sie Ihr Postfach.
              </p>
              <button
                onClick={() => setSent(false)}
                className="mt-6 text-brand-600 text-sm hover:underline"
              >
                Andere E-Mail verwenden
              </button>
            </div>
          ) : (
            <>
              <h2 className="text-xl font-semibold text-gray-900 mb-6">Anmelden</h2>

              {/* Mode toggle */}
              <div className="flex rounded-lg border border-gray-200 p-1 mb-6">
                <button
                  type="button"
                  onClick={() => setMode('password')}
                  className={`flex-1 py-1.5 text-sm rounded-md font-medium transition-colors ${
                    mode === 'password' ? 'bg-brand-500 text-white' : 'text-gray-500 hover:text-gray-700'
                  }`}
                >
                  Passwort
                </button>
                <button
                  type="button"
                  onClick={() => setMode('magic')}
                  className={`flex-1 py-1.5 text-sm rounded-md font-medium transition-colors ${
                    mode === 'magic' ? 'bg-brand-500 text-white' : 'text-gray-500 hover:text-gray-700'
                  }`}
                >
                  Magic Link
                </button>
              </div>

              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
                    E-Mail-Adresse
                  </label>
                  <input
                    id="email"
                    type="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="admin@ihre-innung.de"
                    className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent"
                  />
                </div>

                {mode === 'password' && (
                  <div>
                    <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
                      Passwort
                    </label>
                    <input
                      id="password"
                      type="password"
                      required
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      placeholder="••••••••"
                      className="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent"
                    />
                  </div>
                )}

                {error && (
                  <p className="text-sm text-red-600 bg-red-50 px-4 py-2 rounded-lg">{error}</p>
                )}

                <button
                  type="submit"
                  disabled={loading}
                  className="w-full bg-brand-500 text-white py-2.5 px-4 rounded-lg font-medium hover:bg-brand-600 disabled:opacity-60 disabled:cursor-not-allowed transition-colors"
                >
                  {loading
                    ? 'Bitte warten...'
                    : mode === 'password'
                    ? 'Anmelden'
                    : 'Magic Link senden'}
                </button>
              </form>

              {mode === 'password' && (
                <p className="mt-4 text-center text-xs text-gray-400">
                  Demo: admin@demo.de / demo1234
                </p>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  )
}
