"use client";

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { use } from 'react';
import '@/styles/Auth.css';

export default function ResetPasswordPage({ params }: { params: Promise<{ token: string }> }) {
    const { token } = use(params);
    const router = useRouter();
    const [formData, setFormData] = useState({
        password: '',
        confirmPassword: '',
    });
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [success, setSuccess] = useState(false);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError('');

        if (formData.password !== formData.confirmPassword) {
            setError('Lösenorden matchar inte');
            return;
        }

        setLoading(true);

        try {
            const res = await fetch('/api/auth/reset-password', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    token,
                    password: formData.password,
                }),
            });

            const data = await res.json();
            if (!res.ok) throw new Error(data.error || 'Något gick fel');

            setSuccess(true);
            setTimeout(() => {
                router.push('/login');
            }, 3000);
        } catch (err: unknown) {
            setError(err instanceof Error ? err.message : 'Ett oväntat fel uppstod');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="auth-page-container">
            <div className="profile-card card-sm">
                <h2 className="auth-title">VÄLJ NYTT LÖSENORD</h2>

                <p className="auth-subtitle">
                    Ange ditt nya önskade lösenord nedan.
                </p>

                {success ? (
                    <div className="text-center">
                        <div className="auth-success">
                            Ditt lösenord har ändrats! Omdirigerar till inloggning...
                        </div>
                    </div>
                ) : (
                    <form className="auth-form" onSubmit={handleSubmit}>
                        <div className="form-group">
                            <label className="form-label">Nytt Lösenord</label>
                            <input
                                id="password"
                                type="password"
                                required
                                className="form-input"
                                value={formData.password}
                                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                            />
                        </div>

                        <div className="form-group">
                            <label className="form-label">Bekräfta Lösenord</label>
                            <input
                                id="confirmPassword"
                                type="password"
                                required
                                className="form-input"
                                value={formData.confirmPassword}
                                onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
                            />
                        </div>

                        {error && (
                            <div className="auth-error">
                                {error}
                            </div>
                        )}

                        <button
                            type="submit"
                            disabled={loading}
                            className="auth-button"
                        >
                            {loading ? 'Uppdaterar...' : 'Spara Lösenord'}
                        </button>
                    </form>
                )}
            </div>
        </div>
    );
}
