'use client'

import { useEffect } from 'react'
import { useActionState } from 'react'
import { changePasswordAndDisableMustChange } from '../actions'

export function ForcePasswordChange({ slug }: { slug: string }) {
    const [state, action, isPending] = useActionState(changePasswordAndDisableMustChange, { success: false, error: '', redirectTo: '' })

    useEffect(() => {
        if (state?.success && state?.redirectTo) {
            window.location.href = state.redirectTo
        }
    }, [state?.success, state?.redirectTo])

    return (
        <div className="bg-white border rounded-xl p-8 max-w-md w-full shadow-sm">
            <div className="mb-6">
                <h1 className="text-xl font-bold text-gray-900 mb-2">Passwort festlegen</h1>
                <p className="text-gray-500 text-sm">
                    Bitte vergeben Sie jetzt ein persönliches Passwort für Ihren Account.
                </p>
            </div>

            <form action={action} className="space-y-4">
                <input type="hidden" name="slug" value={slug} />

                <div>
                    <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Neues Passwort</label>
                    <input
                        name="newPassword"
                        type="password"
                        required
                        minLength={8}
                        placeholder="Mindestens 8 Zeichen"
                        className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-brand-500 outline-none transition-all"
                    />
                </div>

                <div>
                    <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1">Passwort wiederholen</label>
                    <input
                        name="confirmPassword"
                        type="password"
                        required
                        minLength={8}
                        placeholder="••••••••"
                        className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-brand-500 outline-none transition-all"
                    />
                </div>

                {state?.error && (
                    <p className="text-xs text-red-600 bg-red-50 p-2 rounded">{state?.error}</p>
                )}

                <button
                    type="submit"
                    disabled={isPending}
                    className="w-full bg-gray-900 text-white py-2.5 rounded-lg text-sm font-medium hover:bg-gray-800 disabled:opacity-50 transition-all shadow-sm"
                >
                    {isPending ? 'Speichern...' : 'Passwort festlegen'}
                </button>
            </form>
        </div>
    )
}
