'use client';

import { useState, useEffect } from 'react';
import { DashboardHeader } from '@/components/DashboardHeader';
import { 
  Key, 
  Shield, 
  Settings as SettingsIcon, 
  Save, 
  Loader2, 
  CheckCircle2,
  AlertTriangle,
  Globe,
  Database,
  Cpu,
  Monitor,
  Lock,
  ChevronRight
} from 'lucide-react';

type SettingsCategory = 'intelligence' | 'security' | 'interface';

export default function SettingsPage() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [success, setSuccess] = useState(false);
  const [activeTab, setActiveTab] = useState<SettingsCategory>('intelligence');
  const [settings, setSettings] = useState<Record<string, string>>({
    GOOGLE_PLACES_API_KEY: '',
    APIFY_API_TOKEN: '',
    FOURSQUARE_API_KEY: '',
    GLOBAL_SEARCH_API_KEY: '',
    SYSTEM_PIN: '1234'
  });

  useEffect(() => {
    async function loadSettings() {
      try {
        const res = await fetch('/api/settings');
        const data = await res.json();
        if (data.settings) {
          const sObj: Record<string, string> = {};
          data.settings.forEach((s: any) => {
            sObj[s.key] = s.value;
          });
          setSettings(prev => ({ ...prev, ...sObj }));
        }
      } catch (e) {
        console.error('Failed to load settings');
      } finally {
        setLoading(false);
      }
    }
    loadSettings();
  }, []);

  const handleSave = async () => {
    setSaving(true);
    setSuccess(false);
    try {
      const res = await fetch('/api/settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ settings })
      });
      if (res.ok) {
        setSuccess(true);
        setTimeout(() => setSuccess(false), 3000);
      }
    } catch (e) {
      console.error('Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center bg-white">
        <Loader2 className="w-8 h-8 text-slate-900 animate-spin" />
      </div>
    );
  }

  const tabs: { id: SettingsCategory; label: string; icon: any; description: string }[] = [
    { 
      id: 'intelligence', 
      label: 'Intelligence Sources', 
      icon: Cpu, 
      description: 'API nodes for data extraction & scouting' 
    },
    { 
      id: 'security', 
      label: 'Access Protocols', 
      icon: Lock, 
      description: 'PIN management & session security' 
    },
    { 
      id: 'interface', 
      label: 'Interface Metrics', 
      icon: Monitor, 
      description: 'Display preferences & localization' 
    },
  ];

  return (
    <div className="flex-1 flex flex-col bg-[#fcfcfc] text-slate-900 font-sans">

      <main className="flex-1 flex overflow-hidden">
        {/* Sidebar Navigation */}
        <aside className="w-80 border-r border-[#f0f0f0] bg-white p-6 flex flex-col gap-8">
          <div className="px-4">
            <h2 className="font-serif italic text-2xl text-slate-900">Settings</h2>
            <p className="text-[11px] font-bold text-slate-400 uppercase tracking-widest mt-1">Configuration Console</p>
          </div>

          <nav className="flex flex-col gap-1">
            {tabs.map((tab) => {
              const Icon = tab.icon;
              const isActive = activeTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`w-full group flex flex-col gap-0.5 px-4 py-3 rounded-2xl transition-all text-left ${
                    isActive 
                      ? 'bg-slate-50 border border-slate-100 shadow-sm' 
                      : 'hover:bg-slate-50/50'
                  }`}
                >
                  <div className="flex items-center gap-3">
                    <Icon className={`w-4 h-4 ${isActive ? 'text-slate-900' : 'text-slate-400 group-hover:text-slate-600'}`} />
                    <span className={`text-[13px] font-bold ${isActive ? 'text-slate-900' : 'text-slate-500 group-hover:text-slate-900'}`}>
                      {tab.label}
                    </span>
                  </div>
                  <span className="text-[10px] text-slate-400 font-medium ml-7 leading-tight">
                    {tab.description}
                  </span>
                </button>
              );
            })}
          </nav>

          <div className="mt-auto px-4 py-4 bg-slate-50 rounded-2xl border border-slate-100">
             <div className="flex items-center gap-2 mb-2">
                <div className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
                <span className="text-[10px] font-bold text-slate-900 uppercase tracking-wider">System Operational</span>
             </div>
             <p className="text-[10px] text-slate-500 font-medium leading-normal">
                All extraction nodes are currently synchronized with the global backbone.
             </p>
          </div>
        </aside>

        {/* Content Area */}
        <section className="flex-1 overflow-y-auto bg-[#fafafa] p-12">
          <div className="max-w-3xl">
            
            {/* Category Header */}
            <header className="mb-12">
              <div className="flex items-center gap-2 text-[11px] font-bold text-slate-400 uppercase tracking-[0.2em] mb-3">
                <span>System</span>
                <ChevronRight className="w-3 h-3" />
                <span className="text-slate-900">{activeTab}</span>
              </div>
              <h2 className="font-serif text-4xl text-slate-900 leading-tight">
                {tabs.find(t => t.id === activeTab)?.label}
              </h2>
            </header>

            {/* Form Fields */}
            <div className="space-y-10">
              {activeTab === 'intelligence' && (
                <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
                  <IntelligenceCard 
                    label="Google Maps Engine" 
                    id="GOOGLE_PLACES_API_KEY"
                    value={settings.GOOGLE_PLACES_API_KEY}
                    placeholder="AIzaSy..."
                    onChange={(val) => setSettings(p => ({ ...p, GOOGLE_PLACES_API_KEY: val }))}
                    description="Primary node for verified business locations and geographic indexing."
                  />
                  
                  <IntelligenceCard 
                    label="Scraper Backbone (Apify)" 
                    id="APIFY_API_TOKEN"
                    value={settings.APIFY_API_TOKEN}
                    placeholder="apify_api_..."
                    onChange={(val) => setSettings(p => ({ ...p, APIFY_API_TOKEN: val }))}
                    description="Powering deep-web intelligence extraction and contact harvesting."
                  />

                  <IntelligenceCard 
                    label="Secondary Map Discovery (Foursquare)" 
                    id="FOURSQUARE_API_KEY"
                    value={settings.FOURSQUARE_API_KEY || ''}
                    placeholder="fsq3..."
                    onChange={(val) => setSettings(p => ({ ...p, FOURSQUARE_API_KEY: val }))}
                    description="Fallback node for social business signals and popularity metrics."
                  />
                </div>
              )}

              {activeTab === 'security' && (
                <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
                  <div className="bg-white border border-[#f0f0f0] rounded-[32px] p-8 shadow-sm">
                    <div className="flex items-start justify-between gap-12">
                      <div className="space-y-2 max-w-sm">
                        <h3 className="text-[15px] font-bold text-slate-900">Application Access PIN</h3>
                        <p className="text-[12px] text-slate-500 leading-relaxed">
                          A 4-digit security protocol required for initializing high-level data sessions. This is stored locally and never transmitted.
                        </p>
                      </div>
                      <div className="flex-shrink-0">
                        <input 
                          type="text"
                          maxLength={4}
                          className="w-32 bg-slate-50 border border-slate-200 rounded-2xl px-4 py-4 text-center font-mono text-2xl tracking-[0.5em] text-slate-900 focus:border-slate-900 focus:ring-0 transition-all outline-none shadow-glossy-inner"
                          value={settings.SYSTEM_PIN}
                          onChange={e => setSettings(p => ({ ...p, SYSTEM_PIN: e.target.value.replace(/\D/g, '') }))}
                        />
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {activeTab === 'interface' && (
                <div className="bg-white border border-[#f0f0f0] border-dashed rounded-[32px] p-16 flex flex-col items-center justify-center text-center space-y-4 animate-in fade-in slide-in-from-bottom-4 duration-500">
                  <div className="p-4 rounded-full bg-slate-50">
                    <Monitor className="w-8 h-8 text-slate-300" />
                  </div>
                  <div className="space-y-1">
                    <h3 className="text-sm font-bold text-slate-900">Interface Metrics Pending</h3>
                    <p className="text-xs text-slate-400 max-w-xs">Customization protocols are currently under development in the beta laboratory.</p>
                  </div>
                </div>
              )}
            </div>

            {/* Footer / Save */}
            <footer className="mt-20 pt-8 border-t border-slate-200 flex items-center justify-between">
              <div className="flex items-center gap-4 text-slate-400">
                <Shield className="w-4 h-4 opacity-50" />
                <span className="text-[11px] font-medium leading-normal max-w-[240px]">
                  Credentials are encrypted using AES-256 before being committed to your local vault.
                </span>
              </div>

              <button 
                onClick={handleSave}
                disabled={saving}
                className={`group relative px-8 py-3.5 rounded-full font-bold text-[13px] transition-all flex items-center gap-3 active:scale-[0.98] overflow-hidden ${
                  success 
                    ? 'bg-emerald-500 text-white shadow-[0_0_20px_rgba(16,185,129,0.3)]' 
                    : 'bg-slate-900 text-white hover:bg-black shadow-lg hover:shadow-xl'
                }`}
              >
                {saving ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : success ? (
                  <CheckCircle2 className="w-4 h-4 animate-in zoom-in duration-300" />
                ) : (
                  <Save className="w-4 h-4 transition-transform group-hover:-translate-y-0.5" />
                )}
                <span>{success ? 'Protocol Synchronized' : 'Execute Update'}</span>
              </button>
            </footer>

          </div>
        </section>
      </main>
    </div>
  );
}

interface IntelligenceCardProps {
  label: string;
  id: string;
  value: string;
  placeholder: string;
  onChange: (val: string) => void;
  description: string;
}

function IntelligenceCard({ label, id, value, placeholder, onChange, description }: IntelligenceCardProps) {
  return (
    <div className="bg-white border border-[#f0f0f0] rounded-[32px] p-8 shadow-sm hover:shadow-md hover:border-slate-200 transition-all group">
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <label className="text-[13px] font-bold text-slate-900 tracking-tight" htmlFor={id}>
            {label}
          </label>
          <div className="px-2 py-0.5 rounded-md bg-slate-50 text-[9px] font-extrabold text-slate-400 uppercase tracking-widest border border-slate-100">
            Node: {id.split('_')[0].toLowerCase()}
          </div>
        </div>
        
        <div className="relative">
          <input 
            id={id}
            type="password"
            className="w-full bg-slate-50 border border-slate-200 rounded-2xl px-5 py-4 text-sm text-slate-900 placeholder:text-slate-300 focus:border-slate-900 focus:ring-0 transition-all outline-none shadow-glossy-inner' font-mono"
            value={value}
            onChange={e => onChange(e.target.value)}
            placeholder={placeholder}
          />
          <div className="absolute right-4 top-1/2 -translate-y-1/2 p-2 text-slate-300 group-focus-within:text-slate-900 transition-colors">
            <Lock className="w-3.5 h-3.5" />
          </div>
        </div>

        <p className="text-[11px] text-slate-500 font-medium leading-relaxed pl-1">
          {description}
        </p>
      </div>
    </div>
  );
}
