import React, { useState, useEffect } from 'react';
import { EnglishTestForm } from './components/EnglishTestForm';
import { MetaInspector } from './components/MetaInspector';
import { CodeViewer } from './components/CodeViewer';
import { SqliteLeadsViewer } from './components/SqliteLeadsViewer';
import { FormConfigModal } from './components/FormConfigModal';
import { NeuroInsights } from './components/NeuroInsights';
import { MetaTrackingData, CAPIEventRecord, FormConfig, DEFAULT_FORM_CONFIG } from './types';
import { captureCurrentMetaVariables } from './utils/metaTracker';
import { Smartphone, Monitor, Code2, Database, Sliders, Building2, CheckCircle, ArrowRight } from 'lucide-react';

export default function App() {
  const [viewMode, setViewMode] = useState<'mobile' | 'desktop'>('mobile');
  const [activeTab, setActiveTab] = useState<'form' | 'sqlite' | 'code'>('form');
  const [activeOverrides, setActiveOverrides] = useState<Partial<MetaTrackingData>>({});
  const [recentEvents, setRecentEvents] = useState<CAPIEventRecord[]>([]);
  const [formConfig, setFormConfig] = useState<FormConfig>(DEFAULT_FORM_CONFIG);
  const [isConfigModalOpen, setIsConfigModalOpen] = useState<boolean>(false);

  // Fetch recent events from the server on load
  const fetchRecentEvents = async () => {
    try {
      const res = await fetch('/api/meta-events');
      if (res.ok) {
        const data = await res.json();
        setRecentEvents(data.events || []);
      }
    } catch (e) {
      console.warn('Events fetch warning:', e);
    }
  };

  useEffect(() => {
    fetchRecentEvents();
  }, []);

  const handleApplyUrlPreset = (preset: { fbclid: string; utm_source: string; utm_campaign: string }) => {
    const fbc = `fb.1.${Date.now()}.${preset.fbclid}`;
    setActiveOverrides({
      fbclid: preset.fbclid,
      fbc,
      utm_source: preset.utm_source,
      utm_campaign: preset.utm_campaign,
    });
  };

  const handleEventSubmitted = (result: any) => {
    fetchRecentEvents();
  };

  const currentMetaVars = captureCurrentMetaVariables(activeOverrides);

  const activeStepsCount =
    (formConfig.enableQuestion1 ? 1 : 0) + (formConfig.enableQuestion2 ? 1 : 0) + 1;

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 flex flex-col justify-between selection:bg-indigo-500 selection:text-white">
      {/* Top Header - Nom du Business en haut à gauche */}
      <header className="border-b border-slate-800/80 bg-slate-950/80 backdrop-blur sticky top-0 z-30 px-4 sm:px-8 py-3.5 flex flex-wrap items-center justify-between gap-3">
        {/* Business Name & Platform Title at Top Left */}
        <div className="flex items-center gap-3">
          <div className="w-9 h-9 rounded-xl bg-indigo-600/20 border border-indigo-500/40 text-indigo-400 flex items-center justify-center font-bold text-sm shadow-sm">
            <Building2 className="w-5 h-5" />
          </div>
          <div>
            <div className="flex items-center gap-2 flex-wrap">
              <span className="font-extrabold text-white text-base tracking-tight">
                {formConfig.businessName || 'Apex English Academy'}
              </span>
              <span className="text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/60 px-2 py-0.5 rounded-full font-semibold">
                CAPI &bull; SQLite
              </span>
            </div>
            <div className="text-[11px] text-slate-400 flex items-center gap-2">
              <span>Formulaire de qualification mobile-first</span>
              <span className="text-slate-600">&bull;</span>
              <span className="text-emerald-400 font-mono text-[10px]">
                {activeStepsCount} étape{activeStepsCount > 1 ? 's' : ''} active{activeStepsCount > 1 ? 's' : ''}
              </span>
            </div>
          </div>
        </div>

        {/* Action Controls & Navigation Tabs */}
        <div className="flex items-center gap-2 flex-wrap">
          {/* Quick Config Button */}
          <button
            type="button"
            onClick={() => setIsConfigModalOpen(true)}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-slate-700 bg-slate-900 text-slate-200 hover:text-white hover:border-slate-600 text-xs font-medium transition cursor-pointer"
            title="Modifier les questions, la barre de progression ou les champs"
          >
            <Sliders className="w-3.5 h-3.5 text-indigo-400" />
            <span>Paramètres Formulaire</span>
          </button>

          {/* Tab buttons */}
          <div className="bg-slate-900 border border-slate-800 p-1 rounded-xl flex items-center gap-1">
            <button
              type="button"
              onClick={() => setActiveTab('form')}
              className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition cursor-pointer ${
                activeTab === 'form'
                  ? 'bg-indigo-600 text-white shadow-sm'
                  : 'text-slate-400 hover:text-white'
              }`}
            >
              <Smartphone className="w-3.5 h-3.5" />
              <span>Formulaire</span>
            </button>

            <button
              type="button"
              onClick={() => setActiveTab('sqlite')}
              className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition cursor-pointer ${
                activeTab === 'sqlite'
                  ? 'bg-indigo-600 text-white shadow-sm'
                  : 'text-slate-400 hover:text-white'
              }`}
            >
              <Database className="w-3.5 h-3.5 text-amber-400" />
              <span>Base SQLite</span>
            </button>

            <button
              type="button"
              onClick={() => setActiveTab('code')}
              className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition cursor-pointer ${
                activeTab === 'code'
                  ? 'bg-indigo-600 text-white shadow-sm'
                  : 'text-slate-400 hover:text-white'
              }`}
            >
              <Code2 className="w-3.5 h-3.5" />
              <span>Code Source</span>
            </button>
          </div>
        </div>
      </header>

      {/* Main Content Area */}
      <main className="flex-1 max-w-5xl w-full mx-auto p-4 sm:p-6 lg:p-8 space-y-6">
        {/* TAB 1: SQLite Leads Viewer */}
        {activeTab === 'sqlite' && (
          <div className="space-y-4 animate-in fade-in duration-200">
            <SqliteLeadsViewer onRefreshTrigger={fetchRecentEvents} />
          </div>
        )}

        {/* TAB 2: Source Code Viewer */}
        {activeTab === 'code' && (
          <div className="space-y-6 animate-in fade-in duration-200">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div>
                <h2 className="text-xl font-bold text-white mb-1">Code Source & Déploiement CAPI</h2>
                <p className="text-slate-400 text-xs">
                  Code frontend HTML/jQuery généré dynamiquement selon vos réglages et backend PHP avec persistence native SQLite.
                </p>
              </div>
              <button
                type="button"
                onClick={() => setIsConfigModalOpen(true)}
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl border border-indigo-700/60 bg-indigo-950/40 text-indigo-300 hover:bg-indigo-900/40 text-xs font-medium transition"
              >
                <Sliders className="w-3.5 h-3.5" />
                <span>Modifier les étapes & champs</span>
              </button>
            </div>
            <CodeViewer config={formConfig} />
          </div>
        )}

        {/* TAB 3: Interactive Form Preview & Meta Inspector */}
        {activeTab === 'form' && (
          <div className="space-y-6">
            {/* Quick Status Bar for Form Configuration */}
            <div className="bg-slate-900/80 border border-slate-800 rounded-2xl p-3 sm:px-4 flex flex-wrap items-center justify-between gap-2.5 text-xs">
              <div className="flex items-center gap-2 flex-wrap text-slate-300">
                <span className="font-semibold text-white flex items-center gap-1">
                  <span className="w-2 h-2 rounded-full bg-emerald-400" />
                  Flux actif :
                </span>
                <span className="bg-slate-950 border border-slate-800 px-2 py-0.5 rounded text-[11px] text-slate-300 font-mono">
                  {activeStepsCount} étape{activeStepsCount > 1 ? 's' : ''} (
                  {formConfig.enableQuestion1 ? 'Q1: Objectif' : ''}
                  {formConfig.enableQuestion1 && formConfig.enableQuestion2 ? ' &rarr; ' : ''}
                  {formConfig.enableQuestion2 ? 'Q2: Frein' : ''}
                  {(formConfig.enableQuestion1 || formConfig.enableQuestion2) ? ' &rarr; ' : ''}
                  Contact)
                </span>
                <span className="text-slate-500 hidden sm:inline">&bull;</span>
                <span className="text-slate-400 text-[11px]">
                  Champs :{' '}
                  {formConfig.fields.firstName.visible ? 'Prénom' : ''}
                  {formConfig.fields.lastName.visible ? ' + Nom' : ''}
                  {formConfig.fields.email.visible ? ' + Email' : ''}
                  {formConfig.fields.phone.visible ? ' + Mobile' : ''}
                </span>
              </div>

              <div className="flex items-center gap-2">
                {/* Viewport switch */}
                <div className="bg-slate-950 border border-slate-800 p-0.5 rounded-lg flex items-center">
                  <button
                    type="button"
                    onClick={() => setViewMode('mobile')}
                    className={`p-1.5 rounded transition cursor-pointer ${
                      viewMode === 'mobile' ? 'bg-indigo-600 text-white' : 'text-slate-400 hover:text-white'
                    }`}
                    title="Vue Mobile"
                  >
                    <Smartphone className="w-3.5 h-3.5" />
                  </button>
                  <button
                    type="button"
                    onClick={() => setViewMode('desktop')}
                    className={`p-1.5 rounded transition cursor-pointer ${
                      viewMode === 'desktop' ? 'bg-indigo-600 text-white' : 'text-slate-400 hover:text-white'
                    }`}
                    title="Vue Bureau / Écran large"
                  >
                    <Monitor className="w-3.5 h-3.5" />
                  </button>
                </div>

                <button
                  type="button"
                  onClick={() => setIsConfigModalOpen(true)}
                  className="px-2.5 py-1.5 rounded-lg bg-indigo-950/60 border border-indigo-800/60 text-indigo-300 hover:bg-indigo-900/60 font-medium transition cursor-pointer flex items-center gap-1 text-[11px]"
                >
                  <Sliders className="w-3 h-3" />
                  <span>Personnaliser</span>
                </button>
              </div>
            </div>

            {/* Form Presentation Area */}
            <div className="flex justify-center">
              {viewMode === 'mobile' ? (
                /* Mobile Mockup Frame */
                <div className="w-full max-w-[390px] bg-slate-950 border-2 border-slate-800 rounded-[38px] p-3 shadow-2xl relative ring-1 ring-slate-800/60">
                  {/* Smartphone Dynamic Island / Notch */}
                  <div className="w-28 h-4 bg-slate-900 rounded-full mx-auto mb-3 flex items-center justify-center">
                    <div className="w-2.5 h-2.5 rounded-full bg-slate-950 border border-slate-800" />
                  </div>

                  {/* Simulated Mobile Screen Canvas */}
                  <div className="bg-slate-950 rounded-[28px] p-4 min-h-[560px] flex flex-col justify-between overflow-hidden">
                    <EnglishTestForm
                      onEventSubmitted={handleEventSubmitted}
                      activeOverrides={activeOverrides}
                      isEmbeddedMobile={true}
                      config={formConfig}
                      onOpenConfigModal={() => setIsConfigModalOpen(true)}
                    />
                  </div>

                  {/* Home Bar Indicator */}
                  <div className="w-32 h-1 bg-slate-800 rounded-full mx-auto mt-3" />
                </div>
              ) : (
                /* Responsive Fullscreen View */
                <div className="w-full max-w-lg bg-slate-900/60 border border-slate-800/80 rounded-2xl p-6 sm:p-8 shadow-xl">
                  <EnglishTestForm
                    onEventSubmitted={handleEventSubmitted}
                    activeOverrides={activeOverrides}
                    isEmbeddedMobile={false}
                    config={formConfig}
                    onOpenConfigModal={() => setIsConfigModalOpen(true)}
                  />
                </div>
              )}
            </div>

            {/* Real-time Meta Tracking Inspector */}
            <MetaInspector
              currentMetaVars={currentMetaVars}
              recentEvents={recentEvents}
              onApplyUrlPreset={handleApplyUrlPreset}
              onRefreshEvents={fetchRecentEvents}
            />

            {/* Data-Driven Expert Neuro Insights */}
            <NeuroInsights />
          </div>
        )}
      </main>

      {/* Dynamic Form Configuration Modal */}
      <FormConfigModal
        isOpen={isConfigModalOpen}
        onClose={() => setIsConfigModalOpen(false)}
        config={formConfig}
        onChangeConfig={setFormConfig}
      />

      {/* Subtle Footer */}
      <footer className="border-t border-slate-900 py-4 px-6 text-center text-[11px] text-slate-500">
        {formConfig.businessName || 'Apex English Academy'} &bull; Conversions API Meta (v19.0) &bull; Base SQLite &bull; Déduplication SHA-256
      </footer>
    </div>
  );
}
