'use client'

import { useEffect, useState } from 'react'
import { createAuthClient } from 'better-auth/react'

const authClient = createAuthClient({
    // Keep auth requests on the current origin (important for tenant subdomains).
    baseURL: typeof window !== 'undefined'
        ? window.location.origin
        : (process.env.NEXT_PUBLIC_APP_URL ?? 'http://localhost:3032'),
})

interface LoginFormProps {
    primaryColor?: string
}

export function LoginForm({ primaryColor = '#E63946' }: LoginFormProps) {
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState('')
    const [successMessage, setSuccessMessage] = useState('')

    useEffect(() => {
        const params = new URLSearchParams(window.location.search)
        const emailParam = params.get('email')
        if (emailParam) setEmail(emailParam)
        const messageParam = params.get('message')
        if (messageParam === 'password_changed') {
            setSuccessMessage('Passwort erfolgreich geändert. Bitte melden Sie sich mit Ihrem neuen Passwort an.')
        }
    }, [])

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

        const result = await authClient.signIn.email({
            email,
            password,
            callbackURL: '/dashboard',
        })

        setLoading(false)
        if (result.error) {
            setError(result.error.message ?? 'E-Mail oder Passwort falsch.')
            return
        }

        // Use callbackUrl if present, otherwise go to dashboard
        // mustChangePassword is handled by the dashboard ForcePasswordChange component
        const params = new URLSearchParams(window.location.search)
        const callbackUrl = params.get('callbackUrl')
        window.location.href = callbackUrl || '/dashboard'
    }

    return (
        <form onSubmit={handleSubmit} className="space-y-4">
            {successMessage && (
                <p className="text-sm text-green-700 bg-green-50 border border-green-200 px-3 py-2 rounded-lg">
                    {successMessage}
                </p>
            )}

            <div>
                <label
                    htmlFor="email"
                    className="block text-xs font-medium text-gray-600 mb-1 uppercase tracking-wide"
                >
                    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-3 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:border-transparent"
                    style={{ '--tw-ring-color': primaryColor } as any}
                />
            </div>

            <div>
                <label
                    htmlFor="password"
                    className="block text-xs font-medium text-gray-600 mb-1 uppercase tracking-wide"
                >
                    Passwort
                </label>
                <input
                    id="password"
                    type="password"
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="********"
                    className="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:border-transparent"
                    style={{ '--tw-ring-color': primaryColor } as any}
                />
            </div>

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

            <button
                type="submit"
                disabled={loading}
                className="w-full text-white py-2.5 px-4 rounded-lg text-sm font-medium disabled:opacity-60 disabled:cursor-not-allowed transition-colors"
                style={{ backgroundColor: primaryColor }}
            >
                {loading ? 'Bitte warten...' : 'Anmelden'}
            </button>
        </form>
    )
}
