import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Save, Server, Palette, Cpu, BookOpen, Star, Cat, Cloud, Database } from 'lucide-react';
import { AppSettings, ZodiacSign, Familiar, AIProvider } from '../types';
import { Button } from './Button';

interface SettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
  settings: AppSettings;
  onSave: (settings: AppSettings) => void;
}

const zodiacSigns: ZodiacSign[] = ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces'];
const familiars: Familiar[] = ['Cat', 'Owl', 'Toad', 'Bat', 'Crow', 'Wolf', 'None'];

export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, settings, onSave }) => {
  const [localSettings, setLocalSettings] = useState<AppSettings>(settings);
  const [activeTab, setActiveTab] = useState<'general' | 'identity' | 'ai'>('general');

  const handleSave = () => {
    onSave(localSettings);
    onClose();
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          <motion.div 
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50"
            onClick={onClose}
          />
          <motion.div 
            initial={{ scale: 0.9, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.9, opacity: 0 }}
            className="fixed inset-0 flex items-center justify-center z-50 pointer-events-none"
          >
            <div className="glass-panel w-full max-w-lg mx-4 rounded-3xl overflow-hidden pointer-events-auto flex flex-col max-h-[85vh] border border-purple-500/20 shadow-[0_0_50px_rgba(112,0,255,0.2)]">
              
              {/* Header */}
              <div className="p-6 border-b border-white/10 flex justify-between items-center bg-black/40">
                <h2 className="text-2xl font-magical text-purple-300 flex items-center gap-2">
                   <BookOpen size={24} /> The Grimoire
                </h2>
                <button onClick={onClose} className="p-2 hover:bg-white/10 rounded-full transition-colors">
                  <X size={24} className="text-gray-400" />
                </button>
              </div>

              {/* Tabs */}
              <div className="flex p-2 gap-2 bg-black/20 overflow-x-auto">
                 <button onClick={() => setActiveTab('general')} className={`flex-1 py-2 px-3 whitespace-nowrap rounded-xl text-xs font-bold transition-all ${activeTab === 'general' ? 'bg-purple-900/40 text-purple-200 border border-purple-500/30' : 'text-gray-500'}`}>
                   Runes & Colors
                 </button>
                 <button onClick={() => setActiveTab('identity')} className={`flex-1 py-2 px-3 whitespace-nowrap rounded-xl text-xs font-bold transition-all ${activeTab === 'identity' ? 'bg-pink-900/40 text-pink-200 border border-pink-500/30' : 'text-gray-500'}`}>
                   Cosmic Identity
                 </button>
                 <button onClick={() => setActiveTab('ai')} className={`flex-1 py-2 px-3 whitespace-nowrap rounded-xl text-xs font-bold transition-all ${activeTab === 'ai' ? 'bg-blue-900/40 text-blue-200 border border-blue-500/30' : 'text-gray-500'}`}>
                   Brain & Spirit
                 </button>
              </div>

              <div className="p-6 overflow-y-auto custom-scrollbar space-y-6">
                {activeTab === 'general' ? (
                  <>
                    <div>
                      <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3 flex items-center gap-2">
                        <Palette size={14} /> Aura Colors
                      </h3>
                      <div className="grid grid-cols-2 gap-4">
                        <div className="bg-white/5 p-4 rounded-2xl border border-white/5">
                          <label className="text-xs font-semibold text-gray-400 block mb-2">Mom's Aura</label>
                          <input type="color" value={localSettings.momColor} onChange={(e) => setLocalSettings({...localSettings, momColor: e.target.value})} className="w-full h-10 rounded bg-transparent cursor-pointer" />
                        </div>
                        <div className="bg-white/5 p-4 rounded-2xl border border-white/5">
                          <label className="text-xs font-semibold text-gray-400 block mb-2">Dad's Aura</label>
                          <input type="color" value={localSettings.dadColor} onChange={(e) => setLocalSettings({...localSettings, dadColor: e.target.value})} className="w-full h-10 rounded bg-transparent cursor-pointer" />
                        </div>
                      </div>
                    </div>

                    <div>
                      <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3 flex items-center gap-2">
                        <Server size={14} /> Telepathy Link (SSE)
                      </h3>
                      <div className="bg-white/5 p-4 rounded-2xl border border-white/5 space-y-4">
                        <label className="flex items-center gap-3 cursor-pointer">
                          <input type="checkbox" checked={localSettings.enableMcp} onChange={(e) => setLocalSettings({...localSettings, enableMcp: e.target.checked})} className="w-4 h-4 rounded bg-gray-800 border-gray-600 text-purple-500" />
                          <span className="text-sm font-medium text-gray-300">Enable Neural Sync</span>
                        </label>
                        {localSettings.enableMcp && (
                           <input type="text" value={localSettings.mcpServerUrl} onChange={(e) => setLocalSettings({...localSettings, mcpServerUrl: e.target.value})} className="w-full p-3 rounded-xl bg-black/50 border border-white/10 text-gray-300 text-sm font-mono focus:border-purple-500 outline-none" placeholder="http://server..." />
                        )}
                      </div>
                    </div>
                  </>
                ) : activeTab === 'identity' ? (
                  <>
                     <div>
                       <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3 flex items-center gap-2">
                         <Star size={14} /> Star Signs
                       </h3>
                       <div className="grid grid-cols-2 gap-4">
                          <div className="bg-white/5 p-4 rounded-2xl border border-white/5">
                            <label className="text-xs font-semibold text-gray-400 block mb-2">Mom</label>
                            <select value={localSettings.momZodiac} onChange={(e) => setLocalSettings({...localSettings, momZodiac: e.target.value as ZodiacSign})} className="w-full bg-black/50 text-gray-200 text-sm rounded-lg p-2 border border-white/10 outline-none">
                              {zodiacSigns.map(s => <option key={s} value={s}>{s}</option>)}
                            </select>
                          </div>
                          <div className="bg-white/5 p-4 rounded-2xl border border-white/5">
                            <label className="text-xs font-semibold text-gray-400 block mb-2">Dad</label>
                            <select value={localSettings.dadZodiac} onChange={(e) => setLocalSettings({...localSettings, dadZodiac: e.target.value as ZodiacSign})} className="w-full bg-black/50 text-gray-200 text-sm rounded-lg p-2 border border-white/10 outline-none">
                              {zodiacSigns.map(s => <option key={s} value={s}>{s}</option>)}
                            </select>
                          </div>
                       </div>
                     </div>

                     <div>
                       <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3 flex items-center gap-2">
                         <Cat size={14} /> House Familiar
                       </h3>
                       <div className="bg-white/5 p-4 rounded-2xl border border-white/5">
                         <select value={localSettings.familiar} onChange={(e) => setLocalSettings({...localSettings, familiar: e.target.value as Familiar})} className="w-full bg-black/50 text-gray-200 text-sm rounded-lg p-2 border border-white/10 outline-none">
                            {familiars.map(f => <option key={f} value={f}>{f}</option>)}
                         </select>
                         <p className="text-[10px] text-gray-500 mt-2">Your spiritual guardian.</p>
                       </div>
                     </div>
                  </>
                ) : (
                  <>
                    <div>
                       <h3 className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3 flex items-center gap-2">
                         <Cpu size={14} /> Intelligence Source
                       </h3>
                       <div className="flex bg-black/50 p-1 rounded-xl border border-white/10 mb-4">
                          <button 
                            onClick={() => setLocalSettings({...localSettings, aiProvider: 'gemini'})}
                            className={`flex-1 py-2 rounded-lg text-sm font-bold flex items-center justify-center gap-2 transition-all ${localSettings.aiProvider === 'gemini' ? 'bg-purple-600 text-white shadow-lg' : 'text-gray-400 hover:text-white'}`}
                          >
                             <Cloud size={14} /> Gemini
                          </button>
                          <button 
                            onClick={() => setLocalSettings({...localSettings, aiProvider: 'ollama'})}
                            className={`flex-1 py-2 rounded-lg text-sm font-bold flex items-center justify-center gap-2 transition-all ${localSettings.aiProvider === 'ollama' ? 'bg-blue-600 text-white shadow-lg' : 'text-gray-400 hover:text-white'}`}
                          >
                             <Database size={14} /> Ollama
                          </button>
                       </div>
                    </div>

                    {localSettings.aiProvider === 'ollama' && (
                      <div className="space-y-4 animate-fadeIn">
                        <div className="bg-blue-900/10 p-4 rounded-2xl border border-blue-500/20">
                           <h4 className="text-blue-300 font-bold text-sm flex items-center gap-2"><Cpu size={16} /> Local Spirit</h4>
                           <p className="text-blue-400/60 text-xs mt-1">Ensure Ollama is running with CORS enabled.</p>
                        </div>
                        <div>
                          <label className="text-xs font-semibold text-gray-400 block mb-1">URL</label>
                          <input type="text" value={localSettings.ollamaUrl} onChange={(e) => setLocalSettings({...localSettings, ollamaUrl: e.target.value})} className="w-full p-3 rounded-xl bg-black/50 border border-white/10 text-gray-300 text-sm font-mono focus:border-blue-500 outline-none" placeholder="http://localhost:11434" />
                        </div>
                        <div>
                          <label className="text-xs font-semibold text-gray-400 block mb-1">Model</label>
                          <input type="text" value={localSettings.ollamaModel} onChange={(e) => setLocalSettings({...localSettings, ollamaModel: e.target.value})} className="w-full p-3 rounded-xl bg-black/50 border border-white/10 text-gray-300 text-sm font-mono focus:border-blue-500 outline-none" placeholder="llama3" />
                        </div>
                      </div>
                    )}
                  </>
                )}
              </div>
              
              <div className="p-6 border-t border-white/10 bg-black/40">
                <Button onClick={handleSave} className="w-full bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-500 hover:to-blue-500 text-white shadow-lg shadow-purple-900/50">
                  <Save size={18} /> Inscribe Changes
                </Button>
              </div>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
};
