import React, { useState, useEffect } from 'react';
import { X, Save, Lock, User, CheckCircle, AlertCircle, Info } from 'lucide-react';
import { Button } from './Button';
import { supabase, isSupabaseConfigured } from '../lib/supabaseClient';
import { useAuth } from '../context/AuthContext';

interface UserProfile {
  id: string;
  email: string;
  first_name?: string;
  last_name?: string;
  date_of_birth: string;
}

interface SettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
  userProfile: UserProfile | null;
  onUpdate: () => void;
}

export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, userProfile, onUpdate }) => {
  const { user, refreshDemoUser } = useAuth();
  const [activeTab, setActiveTab] = useState<'profile' | 'security'>('profile');
  
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [dateOfBirth, setDateOfBirth] = useState('');
  
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{type: 'success' | 'error', text: string} | null>(null);

  useEffect(() => {
    if (isOpen && userProfile) {
      setFirstName(userProfile.first_name || '');
      setLastName(userProfile.last_name || '');
      setDateOfBirth(userProfile.date_of_birth || '');
      setNewPassword('');
      setConfirmPassword('');
      setMessage(null);
      setActiveTab('profile');
    }
  }, [isOpen, userProfile]);

  const commonInputStyles = "w-full px-4 py-3 rounded-xl border border-gray-300 focus:ring-4 focus:ring-primary/10 focus:border-primary outline-none transition-all bg-white text-black font-medium shadow-sm";

  const handleUpdateProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage(null);
    if (!user) return;

    try {
      if (!isSupabaseConfigured) {
        await new Promise(resolve => setTimeout(resolve, 800));
        setMessage({ type: 'success', text: 'Profil frissítve (Demo Mód).' });
        setTimeout(() => onUpdate(), 1000);
        return;
      }
      const { error: dbError } = await supabase.from('profiles').update({ first_name: firstName, last_name: lastName, date_of_birth: dateOfBirth, updated_at: new Date().toISOString() }).eq('id', user.id);
      if (dbError) throw dbError;
      await supabase.auth.updateUser({ data: { first_name: firstName, last_name: lastName, date_of_birth: dateOfBirth } });
      setMessage({ type: 'success', text: 'Adatok sikeresen mentve.' });
      setTimeout(() => onUpdate(), 1000);
    } catch (err: any) {
      setMessage({ type: 'error', text: 'Hiba: ' + err.message });
    } finally {
      setLoading(false);
    }
  };

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage(null);
    if (newPassword.length < 6) { setMessage({ type: 'error', text: 'Túl rövid jelszó.' }); setLoading(false); return; }
    if (newPassword !== confirmPassword) { setMessage({ type: 'error', text: 'A jelszavak nem egyeznek.' }); setLoading(false); return; }

    try {
      if (!isSupabaseConfigured) {
        await new Promise(resolve => setTimeout(resolve, 800));
        setMessage({ type: 'success', text: 'Jelszó frissítve (Demo Mód).' });
        return;
      }
      const { error } = await supabase.auth.updateUser({ password: newPassword });
      if (error) throw error;
      setMessage({ type: 'success', text: 'Jelszó sikeresen módosítva.' });
      setNewPassword(''); setConfirmPassword('');
    } catch (err: any) {
      setMessage({ type: 'error', text: 'Hiba: ' + err.message });
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm animate-fade-in">
      <div className="bg-white rounded-3xl shadow-2xl w-full max-w-2xl overflow-hidden flex flex-col max-h-[90vh] border border-white/20">
        
        <div className="p-8 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
          <h2 className="text-2xl font-black text-gray-900 tracking-tighter">Fiók Beállítások</h2>
          <button onClick={onClose} className="p-2 hover:bg-gray-200 rounded-full transition-colors bg-white shadow-sm border border-gray-100">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        <div className="flex border-b border-gray-100 bg-white">
          <button onClick={() => { setActiveTab('profile'); setMessage(null); }} className={`flex-1 py-4 text-xs font-black uppercase tracking-widest flex items-center justify-center gap-2 transition-all ${activeTab === 'profile' ? 'text-primary border-b-4 border-primary bg-purple-50/30' : 'text-gray-400 hover:text-gray-600 hover:bg-gray-50'}`}>
            <User className="w-4 h-4" /> Profil
          </button>
          <button onClick={() => { setActiveTab('security'); setMessage(null); }} className={`flex-1 py-4 text-xs font-black uppercase tracking-widest flex items-center justify-center gap-2 transition-all ${activeTab === 'security' ? 'text-primary border-b-4 border-primary bg-purple-50/30' : 'text-gray-400 hover:text-gray-600 hover:bg-gray-50'}`}>
            <Lock className="w-4 h-4" /> Biztonság
          </button>
        </div>

        <div className="p-10 overflow-y-auto bg-white">
          {message && (
            <div className={`mb-8 p-5 rounded-2xl flex items-start gap-4 animate-fade-in ${message.type === 'success' ? 'bg-green-50 text-green-800 border-2 border-green-100' : 'bg-red-50 text-red-800 border-2 border-red-100'}`}>
              {message.type === 'success' ? <CheckCircle className="w-6 h-6 mt-0.5" /> : <AlertCircle className="w-6 h-6 mt-0.5" />}
              <span className="font-bold text-sm">{message.text}</span>
            </div>
          )}

          {activeTab === 'profile' && (
            <form onSubmit={handleUpdateProfile} className="space-y-8">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                <div>
                  <label className="block text-xs font-black text-gray-400 uppercase tracking-widest mb-3">Vezetéknév</label>
                  <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} className={commonInputStyles} />
                </div>
                <div>
                  <label className="block text-xs font-black text-gray-400 uppercase tracking-widest mb-3">Keresztnév</label>
                  <input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} className={commonInputStyles} />
                </div>
              </div>
              
              <div>
                <label className="block text-xs font-black text-gray-400 uppercase tracking-widest mb-3">Születési Dátum</label>
                <input type="date" value={dateOfBirth} onChange={(e) => setDateOfBirth(e.target.value)} className={commonInputStyles} />
              </div>

              <div>
                <label className="block text-xs font-black text-gray-400 uppercase tracking-widest mb-3">E-mail cím</label>
                <input type="email" value={user?.email || ''} disabled className="w-full px-4 py-3 rounded-xl border border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed font-medium" />
              </div>

              <div className="pt-6 border-t border-gray-100 flex justify-end">
                <Button type="submit" disabled={loading} className="font-black uppercase tracking-widest px-10 shadow-lg shadow-primary/20">
                  {loading ? 'Mentés...' : 'Adatok Frissítése'}
                </Button>
              </div>
            </form>
          )}

          {activeTab === 'security' && (
            <form onSubmit={handleChangePassword} className="space-y-8">
              <div>
                <label className="block text-xs font-black text-gray-400 uppercase tracking-widest mb-3">Új Jelszó</label>
                <input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} placeholder="Minimum 6 karakter" className={commonInputStyles} />
              </div>
              
              <div>
                <label className="block text-xs font-black text-gray-400 uppercase tracking-widest mb-3">Jelszó Megerősítése</label>
                <input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} placeholder="Jelszó újra" className={commonInputStyles} />
              </div>

              <div className="bg-blue-50 p-5 rounded-2xl text-sm text-blue-900 border-2 border-blue-100 flex items-start gap-4">
                <Info className="w-6 h-6 flex-shrink-0 text-blue-500" />
                <p className="font-bold leading-relaxed">Biztonsági okokból a jelszó megváltoztatása után javasolt az újra-bejelentkezés minden eszközön.</p>
              </div>

              <div className="pt-6 border-t border-gray-100 flex justify-end">
                <Button type="submit" disabled={loading} className="font-black uppercase tracking-widest px-10 shadow-lg shadow-primary/20">
                  {loading ? 'Folyamatban...' : 'Jelszó Mentése'}
                </Button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};