'use client';


import React, { useState } from 'react';
import { UserProfile, UserPreferences } from '@/lib/types';
import { User, Settings, Globe, Shield, Bell, Save, Camera, Target, Flame, Layout } from 'lucide-react';

interface UserProfileSettingsProps {
    user: UserProfile;
    onUpdate: (updates: Partial<UserProfile>) => void;
    onBack: () => void;
}

const UserProfileSettings: React.FC<UserProfileSettingsProps> = ({ user, onUpdate, onBack }) => {
    // DEBUG: Check props
    console.log("[UserProfileSettings DEBUG] PROPS RECEIVED:", {
        user,
        userId: user?.id,
        hasOnUpdate: !!onUpdate,
        hasOnBack: !!onBack
    });

    const [activeTab, setActiveTab] = useState<'profile' | 'preferences' | 'account'>('profile');
    const [formData, setFormData] = useState({
        name: user.name,
        avatar: user.avatar || '',
        bio: user.bio || '',
        email: user.email,
        theme: user.preferences.theme,
        dailyWordGoal: user.preferences.dailyWordGoal
    });

    const fileInputRef = React.useRef<HTMLInputElement>(null);

    const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (!file) return;
        if (!file.type.startsWith('image/')) {
            alert('Veuillez sélectionner une image valide.');
            return;
        }

        const reader = new FileReader();
        reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
                const MAX_SIZE = 256;
                let width = img.width;
                let height = img.height;

                if (width > height && width > MAX_SIZE) {
                    height = Math.round((height * MAX_SIZE) / width);
                    width = MAX_SIZE;
                } else if (height > MAX_SIZE) {
                    width = Math.round((width * MAX_SIZE) / height);
                    height = MAX_SIZE;
                }

                const canvas = document.createElement('canvas');
                canvas.width = width;
                canvas.height = height;
                const ctx = canvas.getContext('2d');
                if (ctx) {
                    ctx.drawImage(img, 0, 0, width, height);
                    const dataUrl = canvas.toDataURL('image/jpeg', 0.8);
                    setFormData(prev => ({ ...prev, avatar: dataUrl }));
                }
            };
            img.src = e.target?.result as string;
        };
        reader.readAsDataURL(file);
    };

    const handleSave = () => {
        onUpdate({
            name: formData.name,
            avatar: formData.avatar,
            bio: formData.bio,
            email: formData.email,
            preferences: {
                ...user.preferences,
                theme: formData.theme,
                dailyWordGoal: formData.dailyWordGoal
            }
        });
        alert("Profil mis à jour !");
    };

    const isDark = formData.theme === 'dark';
    const isSepia = formData.theme === 'sepia';

    const themeOuterClass = isDark ? 'bg-slate-900 text-white' : isSepia ? 'bg-[#eaddc4] text-[#433422]' : 'bg-slate-50 text-slate-900';
    const themeInnerClass = isDark ? 'bg-slate-800 border-slate-700' : isSepia ? 'bg-[#f4ecd8] border-[#dfcdae]' : 'bg-white border-slate-200';
    const themeTextHeading = isDark ? 'text-white' : isSepia ? 'text-[#332616]' : 'text-slate-900';
    const themeTextMuted = isDark ? 'text-slate-400' : isSepia ? 'text-[#735e44]' : 'text-slate-500';
    const themeInputBg = isDark ? 'bg-slate-900 border-slate-700 text-white' : isSepia ? 'bg-[#fbf8f1] border-[#eaddc4] text-[#433422]' : 'bg-slate-50 border-slate-200 text-slate-900';
    const themeTabActive = isDark ? 'bg-white text-slate-900 shadow-lg' : isSepia ? 'bg-[#5c4731] text-white shadow-lg' : 'bg-slate-900 text-white shadow-lg';
    const themeTabInactive = isDark ? 'text-slate-400 hover:bg-slate-800 hover:text-white' : isSepia ? 'text-[#735e44] hover:bg-[#eaddc4] hover:text-[#332616]' : 'text-slate-500 hover:bg-white hover:text-slate-900';

    return (
        <div className={`h-screen overflow-y-auto p-8 font-sans ${themeOuterClass}`}>
            <div className="max-w-4xl mx-auto">
                <div className="flex justify-between items-center mb-10">
                    <div>
                        <h1 className={`text-3xl font-black ${themeTextHeading}`}>Mon Compte</h1>
                        <p className={themeTextMuted}>Gérez vos informations personnelles et préférences d'écriture.</p>
                    </div>
                    <button onClick={onBack} className={`${themeInnerClass} px-4 py-2 rounded-lg text-sm font-bold opacity-80 hover:opacity-100 transition-opacity`}>Fermer</button>
                </div>

                <div className="flex flex-col md:flex-row gap-8">
                    {/* Sidebar Navigation */}
                    <div className="w-full md:w-64 space-y-1">
                        <button
                            onClick={() => setActiveTab('profile')}
                            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-bold transition-all ${activeTab === 'profile' ? themeTabActive : themeTabInactive}`}
                        >
                            <User size={18} /> Profil Public
                        </button>
                        <button
                            onClick={() => setActiveTab('preferences')}
                            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-bold transition-all ${activeTab === 'preferences' ? themeTabActive : themeTabInactive}`}
                        >
                            <Layout size={18} /> Interface & Écriture
                        </button>
                        <button
                            onClick={() => setActiveTab('account')}
                            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-bold transition-all ${activeTab === 'account' ? themeTabActive : themeTabInactive}`}
                        >
                            <Shield size={18} /> Sécurité & Plan
                        </button>
                    </div>

                    {/* Main Content Pane */}
                    <div className={`flex-1 rounded-2xl shadow-sm border p-8 ${themeInnerClass}`}>
                        {activeTab === 'profile' && (
                            <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-300">
                                <div className={`flex items-center gap-6 pb-8 border-b ${isDark ? 'border-slate-700' : isSepia ? 'border-[#dfcdae]' : 'border-slate-100'}`}>
                                    <div className="relative group cursor-pointer" onClick={() => fileInputRef.current?.click()}>
                                        <input
                                            type="file"
                                            ref={fileInputRef}
                                            onChange={handleImageUpload}
                                            accept="image/*"
                                            className="hidden"
                                        />
                                        <img src={formData.avatar || 'https://via.placeholder.com/150'} className={`w-24 h-24 rounded-full object-cover border-4 shadow-md ${isDark ? 'border-slate-800' : isSepia ? 'border-[#f4ecd8]' : 'border-slate-50'}`} alt="Avatar" />
                                        <div className="absolute inset-0 bg-black/40 text-white rounded-full opacity-0 group-hover:opacity-100 flex items-center justify-center transition-opacity" title="Changer d'avatar">
                                            <Camera size={20} />
                                        </div>
                                    </div>
                                    <div>
                                        <h3 className={`font-bold text-lg ${themeTextHeading}`}>{user.name}</h3>
                                        <p className={`text-sm ${themeTextMuted}`}>Membre depuis {new Date(user.subscription.startDate).toLocaleDateString('fr-FR', { month: 'long', year: 'numeric' })}</p>
                                        <div className="mt-2 flex gap-4">
                                            <div className="flex items-center gap-1.5 text-xs font-bold text-orange-500">
                                                <Flame size={14} fill="currentColor" /> {user.stats.writingStreak} jours de streak
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 gap-6">
                                    <div className="space-y-1">
                                        <label className={`text-xs font-black uppercase tracking-widest ${themeTextMuted}`}>Nom affiché</label>
                                        <input
                                            type="text"
                                            value={formData.name}
                                            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                            className={`w-full p-3 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 ${themeInputBg}`}
                                        />
                                    </div>

                                    <div className="space-y-1">
                                        <label className={`text-xs font-black uppercase tracking-widest ${themeTextMuted}`}>Bio / Citation inspirante</label>
                                        <textarea
                                            value={formData.bio}
                                            onChange={(e) => setFormData({ ...formData, bio: e.target.value })}
                                            className={`w-full p-3 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 h-24 resize-none ${themeInputBg}`}
                                            placeholder="Partagez quelques mots sur votre style..."
                                        />
                                    </div>
                                </div>
                            </div>
                        )}

                        {activeTab === 'preferences' && (
                            <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-300">
                                <div className="grid grid-cols-1 gap-8">
                                    <div className="space-y-3">
                                        <label className={`text-xs font-black uppercase tracking-widest flex items-center gap-2 ${themeTextMuted}`}>
                                            <Target size={14} /> Objectif quotidien de mots
                                        </label>
                                        <div className="flex items-center gap-4">
                                            <input
                                                type="range" min="0" max="5000" step="100"
                                                value={formData.dailyWordGoal}
                                                onChange={(e) => setFormData({ ...formData, dailyWordGoal: parseInt(e.target.value) })}
                                                className="flex-1 accent-blue-600"
                                            />
                                            <span className="font-mono font-bold text-blue-600 bg-blue-50 px-3 py-1 rounded-lg">{formData.dailyWordGoal}</span>
                                        </div>
                                    </div>

                                    <div className="space-y-3">
                                        <label className={`text-xs font-black uppercase tracking-widest flex items-center gap-2 ${themeTextMuted}`}>
                                            Thème de l'éditeur
                                        </label>
                                        <div className="grid grid-cols-3 gap-3">
                                            {['light', 'sepia', 'dark'].map((t) => (
                                                <button
                                                    key={t}
                                                    onClick={() => setFormData({ ...formData, theme: t as any })}
                                                    className={`p-4 rounded-xl border-2 transition-all flex flex-col items-center gap-2 ${formData.theme === t ? 'border-blue-500 bg-blue-50 text-blue-700' : isDark ? 'border-slate-700 hover:border-slate-600' : isSepia ? 'border-[#dfcdae] hover:border-[#cfbd9e]' : 'border-slate-100 hover:border-slate-200'}`}
                                                >
                                                    <div className={`w-8 h-8 rounded-full border border-slate-200 ${t === 'light' ? 'bg-white' : t === 'sepia' ? 'bg-[#f4ecd8]' : 'bg-slate-900'}`} />
                                                    <span className={`text-[10px] font-bold uppercase ${formData.theme !== t ? themeTextMuted : ''}`}>{t}</span>
                                                </button>
                                            ))}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}

                        {activeTab === 'account' && (
                            <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-300">
                                <div className="p-4 bg-blue-50 border border-blue-100 rounded-xl flex justify-between items-center">
                                    <div>
                                        <h4 className="font-bold text-blue-900">Plan {(user.subscription.planDetails?.displayName || user.subscription.plan).toUpperCase()}</h4>
                                        <p className="text-xs text-blue-700">Abonnement actif</p>
                                    </div>
                                    <button className="bg-blue-600 text-white px-4 py-2 rounded-lg text-xs font-bold hover:bg-blue-700 shadow-md shadow-blue-200">Gérer</button>
                                </div>

                                <div className="space-y-1">
                                    <label className={`text-xs font-black uppercase tracking-widest ${themeTextMuted}`}>Email du compte</label>
                                    <input
                                        type="email"
                                        value={formData.email}
                                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                        className={`w-full p-3 rounded-xl outline-none focus:ring-2 focus:ring-blue-500 ${themeInputBg}`}
                                    />
                                </div>

                                <div className="pt-4">
                                    <button className="text-red-500 text-sm font-bold hover:underline">Supprimer mon compte définitivement</button>
                                </div>
                            </div>
                        )}

                        <div className={`mt-12 pt-8 border-t flex justify-end ${isDark ? 'border-slate-700' : isSepia ? 'border-[#dfcdae]' : 'border-slate-100'}`}>
                            <button
                                onClick={handleSave}
                                className={`px-8 py-3 rounded-xl font-bold flex items-center gap-2 transition-all shadow-xl hover:shadow-blue-200 ${isDark ? 'bg-white text-slate-900 hover:bg-blue-500 hover:text-white' : isSepia ? 'bg-[#5c4731] text-white hover:bg-blue-600' : 'bg-slate-900 text-white hover:bg-blue-600'}`}
                            >
                                <Save size={18} /> Sauvegarder les modifications
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default UserProfileSettings;
