"use client";

import { resetPassword } from "@/app/actions/auth";
import Link from "next/link";
import { useState, Suspense, useTransition } from "react";
import { useSearchParams } from "next/navigation";
import { Eye, EyeOff, Loader2, CheckCircle, AlertCircle, Lock } from "lucide-react";

function PasswordStrength({ password }: { password: string }) {
    const checks = [
        password.length >= 8,
        /[A-Z]/.test(password),
        /\d/.test(password),
        /[^A-Za-z0-9]/.test(password),
    ];
    const score = checks.filter(Boolean).length;
    const colors = ["", "bg-red-500", "bg-orange-500", "bg-yellow-500", "bg-emerald-500"];
    const labels = ["", "Weak", "Fair", "Good", "Strong"];
    if (!password) return null;
    return (
        <div className="mt-2 space-y-1.5">
            <div className="flex gap-1">
                {[1, 2, 3, 4].map((i) => (
                    <div key={i} className={`h-1 flex-1 rounded-full transition-all duration-300 ${i <= score ? colors[score] : "bg-white/10"}`} />
                ))}
            </div>
            <p className={`text-xs ${score >= 3 ? "text-emerald-400" : score >= 2 ? "text-yellow-400" : "text-red-400"}`}>
                {labels[score]}
            </p>
        </div>
    );
}

function ResetPasswordForm() {
    const searchParams = useSearchParams();
    const token = searchParams.get("token");
    const [password, setPassword] = useState("");
    const [confirm, setConfirm] = useState("");
    const [showPass, setShowPass] = useState(false);
    const [success, setSuccess] = useState(false);
    const [error, setError] = useState("");
    const [isPending, startTransition] = useTransition();

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        setError("");
        if (password !== confirm) { setError("Passwords do not match."); return; }
        if (!token) { setError("Invalid or missing reset token."); return; }
        startTransition(async () => {
            const result = await resetPassword(token, password);
            if (result?.error) setError(result.error);
            else setSuccess(true);
        });
    };

    if (!token) {
        return (
            <div className="text-center py-4">
                <div className="w-14 h-14 rounded-full bg-red-500/15 border border-red-500/30 flex items-center justify-center mx-auto mb-4">
                    <AlertCircle className="w-7 h-7 text-red-400" />
                </div>
                <h2 className="text-xl font-bold text-white mb-2">Invalid link</h2>
                <p className="text-sm text-slate-400 mb-6">This reset link is missing a token. Please request a new one.</p>
                <Link href="/forgot-password" className="px-5 py-2.5 rounded-xl bg-[#0070f3] text-white text-sm font-semibold hover:bg-[#0060d3] transition-colors">
                    Request new link
                </Link>
            </div>
        );
    }

    if (success) {
        return (
            <div className="text-center py-4">
                <div className="w-14 h-14 rounded-full bg-emerald-500/15 border border-emerald-500/30 flex items-center justify-center mx-auto mb-4">
                    <CheckCircle className="w-7 h-7 text-emerald-400" />
                </div>
                <h2 className="text-xl font-bold text-white mb-2">Password updated!</h2>
                <p className="text-sm text-slate-400 mb-6">You can now sign in with your new password.</p>
                <Link href="/login" className="px-5 py-2.5 rounded-xl bg-[#0070f3] text-white text-sm font-semibold hover:bg-[#0060d3] transition-colors">
                    Sign in
                </Link>
            </div>
        );
    }

    return (
        <>
            <div className="mb-7">
                <h1 className="text-2xl font-bold text-white mb-1.5">Create new password</h1>
                <p className="text-sm text-slate-400">Choose a strong password for your account.</p>
            </div>
            <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                    <label className="block text-sm font-medium text-slate-300 mb-1.5">New Password</label>
                    <div className="relative">
                        <Lock className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
                        <input type={showPass ? "text" : "password"} value={password} onChange={(e) => setPassword(e.target.value)} required
                            className="w-full pl-10 pr-11 py-3 rounded-xl bg-white/5 border border-white/10 text-white placeholder-slate-500 focus:border-[#0070f3]/60 focus:ring-2 focus:ring-[#0070f3]/20 outline-none transition-all text-sm"
                            placeholder="Minimum 8 characters" />
                        <button type="button" onClick={() => setShowPass(!showPass)} className="absolute right-3.5 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300 transition-colors">
                            {showPass ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                        </button>
                    </div>
                    <PasswordStrength password={password} />
                </div>
                <div>
                    <label className="block text-sm font-medium text-slate-300 mb-1.5">Confirm Password</label>
                    <div className="relative">
                        <Lock className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
                        <input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} required
                            className={`w-full pl-10 pr-4 py-3 rounded-xl bg-white/5 border text-white placeholder-slate-500 focus:ring-2 outline-none transition-all text-sm ${confirm && password !== confirm ? "border-red-500/50 focus:ring-red-500/20 focus:border-red-500/60" : "border-white/10 focus:border-[#0070f3]/60 focus:ring-[#0070f3]/20"}`}
                            placeholder="Repeat your password" />
                    </div>
                    {confirm && password !== confirm && <p className="text-xs text-red-400 mt-1">Passwords do not match</p>}
                </div>
                {error && <p className="text-sm text-red-400 bg-red-500/10 border border-red-500/20 rounded-lg px-3 py-2">{error}</p>}
                <button type="submit" disabled={isPending || password !== confirm || !password}
                    className="w-full py-3 rounded-xl bg-[#0070f3] text-white font-semibold hover:bg-[#0060d3] transition-all shadow-lg shadow-[#0070f3]/25 disabled:opacity-50 flex items-center justify-center gap-2">
                    {isPending ? <><Loader2 className="w-4 h-4 animate-spin" /> Updating...</> : "Update Password"}
                </button>
            </form>
            <div className="mt-6 text-center">
                <Link href="/login" className="text-sm text-slate-400 hover:text-white transition-colors">Back to sign in</Link>
            </div>
        </>
    );
}

export default function ResetPasswordPage() {
    return (
        <div className="min-h-screen flex flex-col items-center justify-center px-4"
            style={{ background: "radial-gradient(ellipse 80% 60% at 50% -10%, #0d1f3c 0%, #0a0a0f 70%)" }}>
            <div className="flex items-center gap-2.5 mb-8">
                <div className="w-9 h-9 rounded-xl bg-[#0070f3] flex items-center justify-center shadow-lg shadow-[#0070f3]/30">
                    <svg viewBox="0 0 24 24" fill="white" className="w-5 h-5"><path d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>
                </div>
                <span className="text-xl font-bold text-white">Proten<span className="text-[#0070f3]">Connect</span></span>
            </div>
            <div className="w-full max-w-[420px] bg-white/[0.04] border border-white/10 rounded-2xl p-8 backdrop-blur-xl shadow-2xl">
                <Suspense fallback={<div className="text-slate-400 text-sm text-center py-8">Loading...</div>}>
                    <ResetPasswordForm />
                </Suspense>
            </div>
        </div>
    );
}
