import { useState, type FormEvent } from 'react';
import { useAuthStore } from '../store/useAuthStore';
import { changePassword, updateProfile, deleteAccount } from '../services/auth';
import { deleteGraphPresetsByPatient, deleteTestsByPatient } from '../services/medical';
import { useActivePatientId } from '../hooks/useActivePatientId';
import {
    User, Mail, Lock, Shield, AlertCircle, Check, Trash2, AlertTriangle, FileX, FolderX,
    Plus, X, Droplets, Activity, Ruler, Scale, ChevronDown,
} from 'lucide-react';

type CleanupTarget = 'presets' | 'tests';

export function SettingsPage() {
    const user = useAuthStore((s) => s.user);
    const logout = useAuthStore((s) => s.logout);
    const updateUser = useAuthStore((s) => s.updateUser);
    const activePatientId = useActivePatientId();

    // ── Profile state ──
    const [username, setUsername] = useState(user?.username ?? '');
    const [dispName, setDispName] = useState(user?.dispName ?? '');
    const [email, setEmail] = useState(user?.email ?? '');
    const [profileMsg, setProfileMsg] = useState('');
    const [profileErr, setProfileErr] = useState('');
    const [profileSaving, setProfileSaving] = useState(false);
    
    // ── Medical state ──
    const [bloodType, setBloodType] = useState(user?.bloodType ?? '');
    const [allergies, setAllergies] = useState<string[]>(user?.allergies ?? []);
    const [newAllergy, setNewAllergy] = useState('');
    const [medicalMsg, setMedicalMsg] = useState('');
    const [medicalErr, setMedicalErr] = useState('');
    const [medicalSaving, setMedicalSaving] = useState(false);
    const [height, setHeight] = useState(user?.height?.toString() ?? '');
    const [weight, setWeight] = useState(user?.weight?.toString() ?? '');

    // ── Password state ──
    const [curPwd, setCurPwd] = useState('');
    const [newPwd, setNewPwd] = useState('');
    const [confirmPwd, setConfirmPwd] = useState('');
    const [pwdMsg, setPwdMsg] = useState('');
    const [pwdErr, setPwdErr] = useState('');
    const [pwdSaving, setPwdSaving] = useState(false);

    // ── Delete state ──
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
    const [deleteInput, setDeleteInput] = useState('');
    const [deleteErr, setDeleteErr] = useState('');
    const [deleting, setDeleting] = useState(false);

    // ── Cleanup state ──
    const [cleanupTarget, setCleanupTarget] = useState<CleanupTarget | null>(null);
    const [cleanupConfirm, setCleanupConfirm] = useState('');
    const [cleanupErr, setCleanupErr] = useState('');
    const [cleanupMsg, setCleanupMsg] = useState('');
    const [cleanupDeleting, setCleanupDeleting] = useState(false);

    const inputClass =
        'w-full pl-10 pr-4 py-2.5 rounded-lg border border-gray-200 bg-gray-50/50 text-gray-900 placeholder:text-gray-400 text-sm focus:ring-2 focus:ring-primary/40 focus:border-primary transition-all duration-200';

    // ── Profile handlers ──
    const handleProfileSubmit = async (e: FormEvent) => {
        e.preventDefault();
        if (!username.trim() || !dispName.trim() || !email.trim()) {
            setProfileErr('Username, name and email are required.');
            return;
        }
        setProfileErr('');
        setProfileMsg('');
        setProfileSaving(true);
        try {
            const updated = await updateProfile(user!._id, {
                username: username.trim(),
                dispName: dispName.trim(),
                email: email.trim(),
            });
            updateUser(updated);
            setProfileMsg('Profile updated successfully.');
        } catch (err: unknown) {
            setProfileErr(err instanceof Error ? err.message : 'Failed to update profile.');
            if (err instanceof Error && err.message === 'UsernameAlreadyExists') {
                setProfileErr('That username is already taken.');
            }
        } finally {
            setProfileSaving(false);
        }
    };

    // ── Medical handlers ──
    const handleMedicalSubmit = async (e: FormEvent) => {
        e.preventDefault();
        setMedicalErr('');
        setMedicalMsg('');
        setMedicalSaving(true);
        try {
            const updated = await updateProfile(user!._id, {
                bloodType,
                allergies,
                height: height ? parseFloat(height) : null,
                weight: weight ? parseFloat(weight) : null,
            });
            updateUser(updated);
            setMedicalMsg('Medical information updated successfully.');
        } catch (err: unknown) {
            setMedicalErr(err instanceof Error ? err.message : 'Failed to update medical information.');
        } finally {
            setMedicalSaving(false);
        }
    };

    const handleAddAllergy = (e: FormEvent) => {
        e.preventDefault();
        const trimmed = newAllergy.trim();
        if (trimmed && !allergies.includes(trimmed)) {
            setAllergies([...allergies, trimmed]);
            setNewAllergy('');
        }
    };

    const handleRemoveAllergy = (allergy: string) => {
        setAllergies(allergies.filter((a) => a !== allergy));
    };

    // ── Password handlers ──
    const handlePasswordSubmit = async (e: FormEvent) => {
        e.preventDefault();
        if (!curPwd || !newPwd || !confirmPwd) {
            setPwdErr('Please fill in all fields.');
            return;
        }
        if (newPwd.length < 8) {
            setPwdErr('New password must be at least 8 characters.');
            return;
        }
        if (newPwd !== confirmPwd) {
            setPwdErr('New passwords do not match.');
            return;
        }
        setPwdErr('');
        setPwdMsg('');
        setPwdSaving(true);
        try {
            await changePassword(curPwd, newPwd);
            setPwdMsg('Password changed successfully.');
            setCurPwd('');
            setNewPwd('');
            setConfirmPwd('');
        } catch (err: unknown) {
            const msg = err instanceof Error ? err.message : 'Failed to change password.';
            if (msg === 'InvalidCurrentPassword') {
                setPwdErr('Current password is incorrect.');
            } else {
                setPwdErr(msg);
            }
        } finally {
            setPwdSaving(false);
        }
    };

    // ── Delete handlers ──
    const handleDelete = async () => {
        if (deleteInput !== user?.username) {
            setDeleteErr('Username does not match.');
            return;
        }
        setDeleteErr('');
        setDeleting(true);
        try {
            await deleteAccount(user!._id);
            logout();
        } catch (err: unknown) {
            setDeleteErr(err instanceof Error ? err.message : 'Failed to delete account.');
            setDeleting(false);
        }
    };

    const openCleanupModal = (target: CleanupTarget) => {
        setCleanupTarget(target);
        setCleanupConfirm('');
        setCleanupErr('');
        setCleanupMsg('');
    };

    const closeCleanupModal = () => {
        setCleanupTarget(null);
        setCleanupConfirm('');
        setCleanupErr('');
        setCleanupDeleting(false);
    };

    const handleCleanup = async () => {
        if (!cleanupTarget) {
            return;
        }

        if (cleanupTarget === 'tests' && cleanupConfirm !== 'DELETE') {
            setCleanupErr('Type DELETE to confirm.');
            return;
        }

        setCleanupErr('');
        setCleanupMsg('');
        setCleanupDeleting(true);

        try {
            const patientId = activePatientId;
            if (!patientId) {
                throw new Error('Missing user ID.');
            }

            const result = cleanupTarget === 'tests'
                ? await deleteTestsByPatient(patientId)
                : await deleteGraphPresetsByPatient(patientId);

            setCleanupMsg(
                cleanupTarget === 'tests'
                    ? `Deleted ${result.deletedCount} uploaded test${result.deletedCount === 1 ? '' : 's'}.`
                    : `Deleted ${result.deletedCount} graph preset${result.deletedCount === 1 ? '' : 's'}.`,
            );
            closeCleanupModal();
        } catch (err: unknown) {
            setCleanupErr(err instanceof Error ? err.message : 'Failed to delete data.');
            setCleanupDeleting(false);
        }
    };

    return (
        <div className="max-w-2xl mx-auto space-y-8">
            <div>
                <h1 className="text-2xl font-bold text-gray-900 tracking-tight">Settings</h1>
                <p className="text-sm text-gray-500 mt-1">Manage your account and preferences</p>
            </div>

            {/* ═══ Profile Information ═══ */}
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
                <div className="flex items-center gap-3 mb-6">
                    <div className="w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center">
                        <User className="w-[18px] h-[18px] text-primary" />
                    </div>
                    <div>
                        <h2 className="text-lg font-semibold text-gray-900">Profile Information</h2>
                        <p className="text-xs text-gray-500">Update your display name and email</p>
                    </div>
                </div>

                {profileMsg && (
                    <div className="flex items-center gap-2 mb-4 p-3 rounded-lg bg-green-50 border border-green-100 text-green-700 text-sm">
                        <Check className="w-4 h-4 flex-shrink-0" />
                        <span>{profileMsg}</span>
                    </div>
                )}
                {profileErr && (
                    <div className="flex items-center gap-2 mb-4 p-3 rounded-lg bg-red-50 border border-red-100 text-red-600 text-sm">
                        <AlertCircle className="w-4 h-4 flex-shrink-0" />
                        <span>{profileErr}</span>
                    </div>
                )}

                <form onSubmit={handleProfileSubmit} className="space-y-4">
                    <div>
                        <label htmlFor="settings-username" className="block text-sm font-medium text-gray-700 mb-1.5">
                            Username
                        </label>
                        <div className="relative">
                            <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                            <input
                                id="settings-username"
                                type="text"
                                value={username}
                                onChange={(e) => setUsername(e.target.value)}
                                className={inputClass}
                            />
                        </div>
                    </div>
                    <div>
                        <label htmlFor="settings-dispname" className="block text-sm font-medium text-gray-700 mb-1.5">
                            Display Name
                        </label>
                        <div className="relative">
                            <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                            <input
                                id="settings-dispname"
                                type="text"
                                value={dispName}
                                onChange={(e) => setDispName(e.target.value)}
                                className={inputClass}
                            />
                        </div>
                    </div>
                    <div>
                        <label htmlFor="settings-email" className="block text-sm font-medium text-gray-700 mb-1.5">
                            Email
                        </label>
                        <div className="relative">
                            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                            <input
                                id="settings-email"
                                type="email"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                className={inputClass}
                            />
                        </div>
                    </div>
                    <div className="flex justify-end">
                        <button
                            id="settings-save-profile"
                            type="submit"
                            disabled={profileSaving}
                            className="px-5 py-2 rounded-lg font-medium text-white text-sm
                                bg-gradient-to-r from-primary to-primary/90
                                hover:shadow-lg hover:shadow-primary/25 hover:-translate-y-0.5
                                active:translate-y-0 transition-all duration-300
                                disabled:opacity-60 disabled:cursor-not-allowed"
                        >
                            {profileSaving ? 'Saving…' : 'Save Changes'}
                        </button>
                    </div>
                </form>
            </div>

            {/* ═══ Medical Information ═══ */}
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
                <div className="flex items-center gap-3 mb-6">
                    <div className="w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center">
                        <Activity className="w-[18px] h-[18px] text-blue-600" />
                    </div>
                    <div>
                        <h2 className="text-lg font-semibold text-gray-900">Medical Information</h2>
                        <p className="text-xs text-gray-500">Manage your blood type, allergies, height and weight</p>
                    </div>
                </div>

                {medicalMsg && (
                    <div className="flex items-center gap-2 mb-4 p-3 rounded-lg bg-green-50 border border-green-100 text-green-700 text-sm">
                        <Check className="w-4 h-4 flex-shrink-0" />
                        <span>{medicalMsg}</span>
                    </div>
                )}
                {medicalErr && (
                    <div className="flex items-center gap-2 mb-4 p-3 rounded-lg bg-red-50 border border-red-100 text-red-600 text-sm">
                        <AlertCircle className="w-4 h-4 flex-shrink-0" />
                        <span>{medicalErr}</span>
                    </div>
                )}

                <form onSubmit={handleMedicalSubmit} className="space-y-6">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                            <label htmlFor="settings-blood-type" className="block text-sm font-medium text-gray-700 mb-1.5">
                                Blood Type
                            </label>
                            <div className="relative">
                                <Droplets className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                <select
                                    id="settings-blood-type"
                                    value={bloodType}
                                    onChange={(e) => setBloodType(e.target.value)}
                                    className={`${inputClass} appearance-none pr-10`}
                                >
                                    <option value="">Select Blood Type</option>
                                    {['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'].map((type) => (
                                        <option key={type} value={type}>
                                            {type}
                                        </option>
                                    ))}
                                </select>
                                <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                            </div>
                        </div>

                        <div className="grid grid-cols-2 gap-3">
                            <div>
                                <label htmlFor="settings-height" className="block text-sm font-medium text-gray-700 mb-1.5">
                                    Height (cm)
                                </label>
                                <div className="relative">
                                    <Ruler className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                    <input
                                        id="settings-height"
                                        type="number"
                                        step="0.1"
                                        value={height}
                                        onChange={(e) => setHeight(e.target.value)}
                                        placeholder="175"
                                        className={inputClass}
                                    />
                                </div>
                            </div>
                            <div>
                                <label htmlFor="settings-weight" className="block text-sm font-medium text-gray-700 mb-1.5">
                                    Weight (kg)
                                </label>
                                <div className="relative">
                                    <Scale className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                    <input
                                        id="settings-weight"
                                        type="number"
                                        step="0.1"
                                        value={weight}
                                        onChange={(e) => setWeight(e.target.value)}
                                        placeholder="70"
                                        className={inputClass}
                                    />
                                </div>
                            </div>
                        </div>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            Allergies
                        </label>
                        <div className="flex flex-wrap gap-2 mb-3">
                            {allergies.length === 0 ? (
                                <p className="text-xs text-gray-400 italic">No allergies listed</p>
                            ) : (
                                allergies.map((allergy) => (
                                    <span
                                        key={allergy}
                                        className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-red-50 border border-red-100 text-red-700 text-xs font-medium group"
                                    >
                                        {allergy}
                                        <button
                                            type="button"
                                            onClick={() => handleRemoveAllergy(allergy)}
                                            className="p-0.5 rounded-full hover:bg-red-200/50 transition-colors"
                                        >
                                            <X className="w-3 h-3" />
                                        </button>
                                    </span>
                                ))
                            )}
                        </div>
                        <div className="flex gap-2">
                            <div className="relative flex-1">
                                <Plus className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                <input
                                    type="text"
                                    value={newAllergy}
                                    onChange={(e) => setNewAllergy(e.target.value)}
                                    onKeyDown={(e) => {
                                        if (e.key === 'Enter') {
                                            e.preventDefault();
                                            handleAddAllergy(e);
                                        }
                                    }}
                                    placeholder="Add an allergy (e.g. Peanuts, Penicillin)"
                                    className={inputClass}
                                />
                            </div>
                            <button
                                type="button"
                                onClick={handleAddAllergy}
                                className="px-4 py-2 rounded-lg border border-gray-200 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50 transition-colors"
                            >
                                Add
                            </button>
                        </div>
                    </div>

                    <div className="flex justify-end">
                        <button
                            id="settings-save-medical"
                            type="submit"
                            disabled={medicalSaving}
                            className="px-5 py-2 rounded-lg font-medium text-white text-sm
                                bg-gradient-to-r from-blue-600 to-blue-700
                                hover:shadow-lg hover:shadow-blue-600/25 hover:-translate-y-0.5
                                active:translate-y-0 transition-all duration-300
                                disabled:opacity-60 disabled:cursor-not-allowed"
                        >
                            {medicalSaving ? 'Saving…' : 'Save Medical Info'}
                        </button>
                    </div>
                </form>
            </div>

            {/* ═══ Change Password ═══ */}
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
                <div className="flex items-center gap-3 mb-6">
                    <div className="w-9 h-9 rounded-lg bg-amber-50 flex items-center justify-center">
                        <Shield className="w-[18px] h-[18px] text-amber-600" />
                    </div>
                    <div>
                        <h2 className="text-lg font-semibold text-gray-900">Change Password</h2>
                        <p className="text-xs text-gray-500">Update your password to keep your account secure</p>
                    </div>
                </div>

                {pwdMsg && (
                    <div className="flex items-center gap-2 mb-4 p-3 rounded-lg bg-green-50 border border-green-100 text-green-700 text-sm">
                        <Check className="w-4 h-4 flex-shrink-0" />
                        <span>{pwdMsg}</span>
                    </div>
                )}
                {pwdErr && (
                    <div className="flex items-center gap-2 mb-4 p-3 rounded-lg bg-red-50 border border-red-100 text-red-600 text-sm">
                        <AlertCircle className="w-4 h-4 flex-shrink-0" />
                        <span>{pwdErr}</span>
                    </div>
                )}

                <form onSubmit={handlePasswordSubmit} className="space-y-4">
                    <div>
                        <label htmlFor="settings-cur-pwd" className="block text-sm font-medium text-gray-700 mb-1.5">
                            Current Password
                        </label>
                        <div className="relative">
                            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                            <input
                                id="settings-cur-pwd"
                                type="password"
                                value={curPwd}
                                onChange={(e) => setCurPwd(e.target.value)}
                                placeholder="Enter current password"
                                autoComplete="current-password"
                                className={inputClass}
                            />
                        </div>
                    </div>
                    <div>
                        <label htmlFor="settings-new-pwd" className="block text-sm font-medium text-gray-700 mb-1.5">
                            New Password
                        </label>
                        <div className="relative">
                            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                            <input
                                id="settings-new-pwd"
                                type="password"
                                value={newPwd}
                                onChange={(e) => setNewPwd(e.target.value)}
                                placeholder="At least 8 characters"
                                autoComplete="new-password"
                                className={inputClass}
                            />
                        </div>
                    </div>
                    <div>
                        <label htmlFor="settings-confirm-pwd" className="block text-sm font-medium text-gray-700 mb-1.5">
                            Confirm New Password
                        </label>
                        <div className="relative">
                            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                            <input
                                id="settings-confirm-pwd"
                                type="password"
                                value={confirmPwd}
                                onChange={(e) => setConfirmPwd(e.target.value)}
                                placeholder="Re-enter new password"
                                autoComplete="new-password"
                                className={inputClass}
                            />
                        </div>
                    </div>
                    <div className="flex justify-end">
                        <button
                            id="settings-save-password"
                            type="submit"
                            disabled={pwdSaving}
                            className="px-5 py-2 rounded-lg font-medium text-white text-sm
                                bg-gradient-to-r from-amber-500 to-amber-600
                                hover:shadow-lg hover:shadow-amber-500/25 hover:-translate-y-0.5
                                active:translate-y-0 transition-all duration-300
                                disabled:opacity-60 disabled:cursor-not-allowed"
                        >
                            {pwdSaving ? 'Changing…' : 'Change Password'}
                        </button>
                    </div>
                </form>
            </div>

            {/* ═══ Data Cleanup ═══ */}
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
                <div className="flex items-center gap-3 mb-4">
                    <div className={`w-9 h-9 rounded-lg flex items-center justify-center ${cleanupTarget === 'tests' ? 'bg-amber-50' : cleanupTarget === 'presets' ? 'bg-red-50' : 'bg-slate-100'}`}>
                        <Trash2 className={`w-[18px] h-[18px] ${cleanupTarget === 'tests' ? 'text-amber-600' : cleanupTarget === 'presets' ? 'text-red-600' : 'text-slate-600'}`} />
                    </div>
                    <div>
                        <h2 className={`text-lg font-semibold ${cleanupTarget === 'tests' ? 'text-amber-600' : cleanupTarget === 'presets' ? 'text-red-600' : 'text-gray-900'}`}>
                            {cleanupTarget === 'tests'
                                ? 'Delete all uploaded tests'
                                : cleanupTarget === 'presets'
                                    ? 'Delete all graph presets'
                                    : 'Data Cleanup'}
                        </h2>
                        <p className="text-xs text-gray-500">
                            {cleanupTarget === 'tests'
                                ? 'Permanently remove every test record you have uploaded.'
                                : cleanupTarget === 'presets'
                                    ? 'Permanently remove every graph preset you have saved.'
                                    : 'Remove all graph presets or uploaded tests from your account'}
                        </p>
                    </div>
                </div>

                {cleanupMsg && !cleanupTarget && (
                    <div className="mb-4 flex items-center gap-2 rounded-lg border border-green-100 bg-green-50 p-3 text-sm text-green-700">
                        <Check className="h-4 w-4 shrink-0" />
                        <span>{cleanupMsg}</span>
                    </div>
                )}

                {!cleanupTarget ? (
                    <div className="flex flex-col gap-3 sm:flex-row">
                        <button
                            id="settings-delete-presets-start"
                            type="button"
                            onClick={() => openCleanupModal('presets')}
                            className="inline-flex items-center justify-center gap-2 rounded-lg border border-red-200 bg-red-50 px-5 py-2.5 text-sm font-medium text-red-600 transition hover:border-red-300 hover:bg-red-100"
                        >
                            <FolderX className="h-4 w-4" />
                            Delete All Presets
                        </button>
                        <button
                            id="settings-delete-tests-start"
                            type="button"
                            onClick={() => openCleanupModal('tests')}
                            className="inline-flex items-center justify-center gap-2 rounded-lg border border-red-200 bg-red-50 px-5 py-2.5 text-sm font-medium text-red-600 transition hover:border-red-300 hover:bg-red-100"
                        >
                            <FileX className="h-4 w-4" />
                            Delete All Tests
                        </button>
                    </div>
                ) : cleanupTarget === 'tests' ? (
                    <div className="space-y-4">
                        <div className="flex items-start gap-2 text-sm text-amber-700">
                            <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0" />
                            <p>
                                To confirm, type <strong className="font-mono bg-amber-100 px-1 rounded">DELETE</strong> below.
                            </p>
                        </div>

                        {cleanupErr && (
                            <div className="flex items-center gap-2 p-3 rounded-lg bg-red-50 border border-red-200 text-red-600 text-sm">
                                <AlertCircle className="w-4 h-4 flex-shrink-0" />
                                <span>{cleanupErr}</span>
                            </div>
                        )}

                        <input
                            id="bulk-cleanup-confirm"
                            type="text"
                            value={cleanupConfirm}
                            onChange={(e) => setCleanupConfirm(e.target.value)}
                            placeholder="Type DELETE to confirm"
                            className="w-full rounded-lg border border-gray-200 bg-gray-50 px-4 py-2.5 text-sm text-gray-900 placeholder:text-gray-400 focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all duration-200"
                        />

                        <div className="flex items-center gap-3">
                            <button
                                type="button"
                                onClick={handleCleanup}
                                disabled={cleanupDeleting || cleanupConfirm !== 'DELETE'}
                                className="px-5 py-2 rounded-lg font-medium text-white text-sm bg-gradient-to-r from-red-500 to-red-600 hover:shadow-lg hover:shadow-red-500/25 hover:-translate-y-0.5 active:translate-y-0 transition-all duration-300 disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:translate-y-0 disabled:hover:shadow-none"
                            >
                                {cleanupDeleting ? 'Deleting…' : 'Delete All Tests'}
                            </button>
                            <button
                                type="button"
                                onClick={closeCleanupModal}
                                className="px-5 py-2 rounded-lg font-medium text-gray-600 text-sm border border-gray-200 bg-white hover:bg-gray-50 transition-all duration-200"
                            >
                                Cancel
                            </button>
                        </div>
                    </div>
                ) : (
                    <div className="space-y-4">
                        {cleanupErr && (
                            <div className="flex items-center gap-2 p-3 rounded-lg bg-red-50 border border-red-200 text-red-600 text-sm">
                                <AlertCircle className="w-4 h-4 flex-shrink-0" />
                                <span>{cleanupErr}</span>
                            </div>
                        )}

                        <div className="flex items-center gap-3">
                            <button
                                type="button"
                                onClick={handleCleanup}
                                disabled={cleanupDeleting}
                                className="px-5 py-2 rounded-lg font-medium text-white text-sm bg-gradient-to-r from-red-500 to-red-600 hover:shadow-lg hover:shadow-red-500/25 hover:-translate-y-0.5 active:translate-y-0 transition-all duration-300 disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:translate-y-0 disabled:hover:shadow-none"
                            >
                                {cleanupDeleting ? 'Deleting…' : 'Delete All Presets'}
                            </button>
                            <button
                                type="button"
                                onClick={closeCleanupModal}
                                className="px-5 py-2 rounded-lg font-medium text-gray-600 text-sm border border-gray-200 bg-white hover:bg-gray-50 transition-all duration-200"
                            >
                                Cancel
                            </button>
                        </div>
                    </div>
                )}
            </div>

            {/* ═══ Delete Account ═══ */}
            <div className="bg-white rounded-2xl border border-red-100 shadow-sm p-6">
                <div className="flex items-center gap-3 mb-4">
                    <div className="w-9 h-9 rounded-lg bg-red-50 flex items-center justify-center">
                        <Trash2 className="w-[18px] h-[18px] text-red-500" />
                    </div>
                    <div>
                        <h2 className="text-lg font-semibold text-red-600">Danger Zone</h2>
                        <p className="text-xs text-gray-500">Permanently delete your account and all data</p>
                    </div>
                </div>

                {!showDeleteConfirm ? (
                    <button
                        id="settings-delete-start"
                        type="button"
                        onClick={() => setShowDeleteConfirm(true)}
                        className="px-5 py-2 rounded-lg font-medium text-red-600 text-sm
                            border border-red-200 bg-red-50
                            hover:bg-red-100 hover:border-red-300
                            transition-all duration-200"
                    >
                        Delete Account
                    </button>
                ) : (
                    <div className="mt-2 p-4 rounded-xl bg-red-50/50 border border-red-100 space-y-4">
                        <div className="flex items-start gap-2 text-sm text-red-600">
                            <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0" />
                            <p>
                                This action is <strong>irreversible</strong>. All your medical records, prescriptions, and data will be permanently deleted.
                                Type <strong className="font-mono bg-red-100 px-1 rounded">{user?.username}</strong> to confirm.
                            </p>
                        </div>

                        {deleteErr && (
                            <div className="flex items-center gap-2 p-3 rounded-lg bg-red-50 border border-red-200 text-red-600 text-sm">
                                <AlertCircle className="w-4 h-4 flex-shrink-0" />
                                <span>{deleteErr}</span>
                            </div>
                        )}

                        <input
                            id="settings-delete-confirm-input"
                            type="text"
                            value={deleteInput}
                            onChange={(e) => setDeleteInput(e.target.value)}
                            placeholder="Type your username to confirm"
                            className="w-full px-4 py-2.5 rounded-lg border border-red-200 bg-white text-gray-900 placeholder:text-gray-400 text-sm focus:ring-2 focus:ring-red-400/40 focus:border-red-400 transition-all duration-200"
                        />

                        <div className="flex items-center gap-3">
                            <button
                                id="settings-delete-confirm"
                                type="button"
                                onClick={handleDelete}
                                disabled={deleting || deleteInput !== user?.username}
                                className="px-5 py-2 rounded-lg font-medium text-white text-sm
                                    bg-gradient-to-r from-red-500 to-red-600
                                    hover:shadow-lg hover:shadow-red-500/25 hover:-translate-y-0.5
                                    active:translate-y-0 transition-all duration-300
                                    disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:translate-y-0 disabled:hover:shadow-none"
                            >
                                {deleting ? 'Deleting…' : 'Permanently Delete'}
                            </button>
                            <button
                                type="button"
                                onClick={() => {
                                    setShowDeleteConfirm(false);
                                    setDeleteInput('');
                                    setDeleteErr('');
                                }}
                                className="px-5 py-2 rounded-lg font-medium text-gray-600 text-sm
                                    border border-gray-200 bg-white
                                    hover:bg-gray-50 transition-all duration-200"
                            >
                                Cancel
                            </button>
                        </div>
                    </div>
                )}
            </div>

        </div>
    );
}
