import { useState, useEffect, useRef } from 'react';
import './App.css';
import type { Session } from '@supabase/supabase-js';
import { supabase } from './pages/supabaseClient';

import Login from './pages/Login';
import ResetPassword from './pages/ResetPassword';
import MemberAdmin from './pages/MemberAdmin';
import BusinessPartners from './pages/BusinessPartners';
import CustomerList from './pages/CustomerList';
import Templates from './pages/Templates';
import Campaign from './pages/Campaign';
import Scheduler from './pages/Scheduler';
import Dashboard from './pages/Dashboard';

const OTP_KEY = 'smm_otp_v1';

interface LoginLog {
  email: string;
  ip_address: string;
  user_agent: string;
  logged_at: string;
}

function MasterSwitcher() {
  const [view, setView]             = useState('bnp');
  const [session, setSession]       = useState<Session | null>(null);
  const [authLoading, setAuthLoading] = useState(true);
  const [isRecovery, setIsRecovery] = useState(false);
  const [otpVerified, setOtpVerified] = useState(false);
  const [showActivity, setShowActivity] = useState(false);
  const [loginLogs, setLoginLogs]   = useState<LoginLog[]>([]);
  const [logsLoading, setLogsLoading] = useState(false);
  const activityRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // On load: if a session exists but no OTP flag in this tab, sign out to force fresh login
    supabase.auth.getSession().then(({ data: { session: s } }) => {
      if (s && sessionStorage.getItem(OTP_KEY) !== '1') {
        supabase.auth.signOut();
        // onAuthStateChange will fire SIGNED_OUT → setSession(null) + setAuthLoading(false)
      } else {
        setSession(s);
        if (s && sessionStorage.getItem(OTP_KEY) === '1') setOtpVerified(true);
        setAuthLoading(false);
      }
    });

    const { data: { subscription } } = supabase.auth.onAuthStateChange((event, s) => {
      setSession(s);
      setAuthLoading(false);
      if (event === 'PASSWORD_RECOVERY') setIsRecovery(true);
      if (event === 'SIGNED_OUT') {
        setIsRecovery(false);
        setOtpVerified(false);
        sessionStorage.removeItem(OTP_KEY);
      }
    });

    return () => subscription.unsubscribe();
  }, []);

  // Close activity dropdown on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (activityRef.current && !activityRef.current.contains(e.target as Node)) {
        setShowActivity(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const handleOtpVerified = () => {
    sessionStorage.setItem(OTP_KEY, '1');
    setOtpVerified(true);
  };

  const handleLogout = async () => {
    sessionStorage.removeItem(OTP_KEY);
    setOtpVerified(false);
    setShowActivity(false);
    await supabase.auth.signOut();
  };

  const handleShowActivity = async () => {
    setShowActivity(v => !v);
    if (!showActivity && loginLogs.length === 0) {
      setLogsLoading(true);
      try {
        const res = await fetch('/api/auth/login-logs');
        setLoginLogs(await res.json());
      } catch { /* ignore */ }
      setLogsLoading(false);
    }
  };

  const userId = session?.user?.id ?? '';

  // ── Loading splash ──
  if (authLoading) {
    return (
      <div className="min-h-screen bg-slate-900 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-2 border-blue-400 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
          <p className="text-slate-500 text-sm">Loading…</p>
        </div>
      </div>
    );
  }

  // ── Password recovery flow ──
  if (isRecovery) {
    return <ResetPassword onComplete={() => setIsRecovery(false)} />;
  }

  // ── Auth gate: no session OR OTP not yet verified ──
  if (!session || !otpVerified) {
    return <Login onOtpVerified={handleOtpVerified} />;
  }

  // ── Main application ──
  return (
    <div className="min-h-screen bg-gray-50">
      <header className="bg-slate-900 text-white p-4 shadow-xl sticky top-0 z-50">
        <div className="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4">

          <h1 className="text-xl font-bold tracking-tight text-blue-400">Sunbelt Mail Matrix</h1>

          <nav className="flex flex-wrap gap-2 bg-slate-800 p-1 rounded-xl border border-slate-700">
            <button onClick={() => setView('bnp')}       className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${view === 'bnp'       ? 'bg-blue-600 text-white'   : 'text-slate-400 hover:text-white'}`}>BNP</button>
            <button onClick={() => setView('b2b')}       className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${view === 'b2b'       ? 'bg-indigo-600 text-white' : 'text-slate-400 hover:text-white'}`}>B2B</button>
            <button onClick={() => setView('b2c')}       className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${view === 'b2c'       ? 'bg-green-600 text-white'  : 'text-slate-400 hover:text-white'}`}>B2C</button>
            <div className="w-px h-6 bg-slate-700 mx-1 hidden md:block" />
            <button onClick={() => setView('templates')} className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${view === 'templates' ? 'bg-amber-600 text-white'   : 'text-slate-400 hover:text-white'}`}>Templates</button>
            <button onClick={() => setView('campaign')}  className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${view === 'campaign'  ? 'bg-rose-600 text-white'    : 'text-slate-400 hover:text-white'}`}>Send Email</button>
            <button onClick={() => setView('scheduler')} className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${view === 'scheduler' ? 'bg-purple-600 text-white'  : 'text-slate-400 hover:text-white'}`}>Scheduler</button>
            <button onClick={() => setView('dashboard')} className={`px-3 py-1.5 rounded-lg text-sm font-medium transition ${view === 'dashboard' ? 'bg-cyan-600 text-white'    : 'text-slate-400 hover:text-white'}`}>Analytics</button>
          </nav>

          <div className="flex items-center gap-3 flex-shrink-0 relative" ref={activityRef}>

            {/* User email + activity toggle */}
            <button
              onClick={handleShowActivity}
              className="flex items-center gap-2 text-slate-400 text-xs hover:text-white transition-colors group"
              title="View login activity"
            >
              <span className="w-2 h-2 bg-emerald-400 rounded-full flex-shrink-0" />
              <span className="hidden md:block truncate max-w-[180px]">{session.user.email}</span>
              <span className="text-slate-600 group-hover:text-slate-400 transition-colors">▾</span>
            </button>

            {/* Sign out */}
            <button
              onClick={handleLogout}
              className="bg-slate-700 hover:bg-red-700 text-slate-300 hover:text-white text-xs font-bold px-3 py-1.5 rounded-lg transition-colors"
            >
              Sign Out
            </button>

            {/* Login Activity Dropdown */}
            {showActivity && (
              <div className="absolute top-full right-0 mt-2 w-96 bg-white rounded-2xl shadow-2xl border border-slate-100 z-50 overflow-hidden">
                <div className="px-5 py-4 border-b border-slate-50 flex items-center justify-between">
                  <h3 className="font-bold text-slate-800 text-sm">Login Activity</h3>
                  <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wider">Last 20 logins</span>
                </div>
                <div className="max-h-80 overflow-y-auto">
                  {logsLoading ? (
                    <div className="p-6 text-center text-slate-400 text-sm">Loading…</div>
                  ) : loginLogs.length === 0 ? (
                    <div className="p-6 text-center text-slate-400 text-sm italic">No login history yet.</div>
                  ) : (
                    loginLogs.map((log, i) => {
                      const d = new Date(log.logged_at);
                      const dateStr = d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                      const timeStr = d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
                      const ua = log.user_agent || '';
                      const browser =
                        ua.includes('Edg')     ? 'Edge' :
                        ua.includes('Chrome')  ? 'Chrome' :
                        ua.includes('Firefox') ? 'Firefox' :
                        ua.includes('Safari')  ? 'Safari' : 'Unknown';
                      const os =
                        ua.includes('Windows') ? 'Windows' :
                        ua.includes('Mac')     ? 'macOS' :
                        ua.includes('iPhone')  ? 'iPhone' :
                        ua.includes('Android') ? 'Android' : '';
                      return (
                        <div key={i} className={`px-5 py-3 border-b border-slate-50 last:border-0 ${i === 0 ? 'bg-blue-50/50' : ''}`}>
                          <div className="flex items-center justify-between gap-2">
                            <span className="text-xs font-bold text-slate-700 truncate">{log.email}</span>
                            {i === 0 && <span className="text-[9px] bg-blue-100 text-blue-700 font-bold px-2 py-0.5 rounded-full flex-shrink-0">Current</span>}
                          </div>
                          <div className="flex items-center gap-3 mt-0.5">
                            <span className="text-[11px] text-slate-500">{dateStr} · {timeStr}</span>
                          </div>
                          <div className="flex items-center gap-2 mt-0.5">
                            <span className="text-[11px] text-slate-400 font-mono">{log.ip_address || '—'}</span>
                            {(browser || os) && (
                              <span className="text-[11px] text-slate-400">· {[browser, os].filter(Boolean).join(' / ')}</span>
                            )}
                          </div>
                        </div>
                      );
                    })
                  )}
                </div>
              </div>
            )}
          </div>

        </div>
      </header>

      <main className="p-4 md:p-8">
        {view === 'bnp'       && <MemberAdmin userId={userId} />}
        {view === 'b2b'       && <BusinessPartners userId={userId} />}
        {view === 'b2c'       && <CustomerList userId={userId} />}
        {view === 'templates' && <Templates userId={userId} />}
        {view === 'campaign'  && <Campaign userId={userId} />}
        {view === 'scheduler' && <Scheduler />}
        {view === 'dashboard' && <Dashboard userId={userId} />}
      </main>
    </div>
  );
}

export default MasterSwitcher;
