import React, { useState } from 'react';
import { useNavigate, Navigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { toast } from 'sonner';
import { Lock, ShieldCheck, LogOut, ArrowLeft } from 'lucide-react';

const LOGO_URL = "/logo.png";

export default function ChangePassword() {
    const { user, changePassword, logout } = useAuth();
    const navigate = useNavigate();
    const [current, setCurrent] = useState('');
    const [next, setNext] = useState('');
    const [confirm, setConfirm] = useState('');
    const [loading, setLoading] = useState(false);

    if (!user) return <Navigate to="/login" replace />;

    const forced = !!user.must_change_password;
    const sanitize = (v) => v.replace(/\D/g, '').slice(0, 6);

    const submit = async (e) => {
        e.preventDefault();
        if (!/^\d{6}$/.test(current)) { toast.error('Code actuel : 6 chiffres'); return; }
        if (!/^\d{6}$/.test(next)) { toast.error('Nouveau code : 6 chiffres'); return; }
        if (next !== confirm) { toast.error('Les deux nouveaux codes ne correspondent pas'); return; }
        if (next === current) { toast.error('Choisis un code différent de l\'actuel'); return; }
        setLoading(true);
        try {
            await changePassword(current, next);
            toast.success('Code mis à jour');
            navigate('/');
        } catch (err) {
            toast.error(err?.response?.data?.detail || 'Erreur');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen flex items-center justify-center bg-[#F8FAFC] p-5">
            <div className="w-full max-w-md rounded-xl border border-slate-200 bg-white shadow-sm p-6 sm:p-8">
                {!forced && (
                    <button
                        type="button"
                        onClick={() => navigate(-1)}
                        className="inline-flex items-center gap-1.5 text-xs font-bold text-slate-500 hover:text-stef mb-4"
                        data-testid="change-password-back"
                    >
                        <ArrowLeft className="h-3.5 w-3.5" /> Retour
                    </button>
                )}

                <div className="flex items-center justify-between mb-6">
                    <div className="flex items-center gap-3">
                        <img src={LOGO_URL} alt="My Truck" className="h-10 w-10 object-contain" />
                        <div>
                            <p className="text-[11px] font-bold uppercase tracking-[0.2em] text-stef">Sécurité</p>
                            <h1 className="font-heading text-xl font-black text-slate-900">
                                {forced ? 'Choisis ton nouveau code' : 'Changer mon code'}
                            </h1>
                        </div>
                    </div>
                </div>

                {forced && (
                    <div className="rounded-md bg-amber-50 border border-amber-200 p-3 mb-5 flex gap-3">
                        <ShieldCheck className="h-4 w-4 text-amber-600 shrink-0 mt-0.5" />
                        <p className="text-xs text-amber-800">
                            Salut <strong>{user.fullname || user.username}</strong>, pour ta première connexion à My Truck tu dois définir un nouveau code personnel à 6 chiffres.
                        </p>
                    </div>
                )}

                <form onSubmit={submit} className="space-y-4" data-testid="change-password-form">
                    <PinField label="Code actuel" value={current} onChange={(v) => setCurrent(sanitize(v))} testid="current-password" autoFocus />
                    <PinField label="Nouveau code" value={next} onChange={(v) => setNext(sanitize(v))} testid="new-password" />
                    <PinField label="Confirme le nouveau code" value={confirm} onChange={(v) => setConfirm(sanitize(v))} testid="confirm-password" />

                    <button
                        data-testid="change-password-submit"
                        type="submit"
                        disabled={loading}
                        className="w-full h-12 rounded-md bg-stef text-white font-heading font-bold tracking-wide hover:bg-stef-hover transition-all disabled:opacity-60 active:scale-[0.99]"
                    >
                        {loading ? 'Mise à jour…' : 'Mettre à jour mon code'}
                    </button>
                </form>

                {forced && (
                    <button
                        type="button"
                        onClick={() => { logout(); navigate('/login'); }}
                        data-testid="change-password-logout"
                        className="mt-4 w-full inline-flex items-center justify-center gap-2 h-10 rounded-md border border-slate-200 text-sm font-semibold text-slate-600 hover:bg-slate-50"
                    >
                        <LogOut className="h-4 w-4" /> Se déconnecter
                    </button>
                )}
            </div>
        </div>
    );
}

function PinField({ label, value, onChange, testid, autoFocus }) {
    return (
        <div>
            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">{label}</label>
            <div className="mt-1.5 relative">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                <input
                    data-testid={testid}
                    type="password"
                    inputMode="numeric"
                    maxLength={6}
                    autoFocus={autoFocus}
                    value={value}
                    onChange={(e) => onChange(e.target.value)}
                    placeholder="••••••"
                    className="w-full h-12 rounded-md border border-slate-300 bg-white pl-10 pr-3 text-2xl font-bold tracking-[0.5em] text-slate-900 placeholder:text-slate-400 placeholder:tracking-[0.5em] text-center focus:border-stef focus:outline-none focus:ring-2 focus:ring-stef/20 transition"
                />
            </div>
        </div>
    );
}
