'use client';

import { useState, useEffect, useRef } from 'react';

interface DashboardHeaderProps {
  activeTab: 'chats' | 'leads' | 'settings' | 'security';
  onChangeTab: (tab: 'chats' | 'leads' | 'settings' | 'security') => void;
  showSettings?: boolean;
  onToggleSettings?: () => void;
}

const ICONS = {
  sun: (
    <svg width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
      <circle cx="12" cy="12" r="4" />
      <path strokeLinecap="round" d="M12 2v2m0 16v2M4.9 4.9l1.4 1.4m11.4 11.4l1.4 1.4M2 12h2m16 0h2M4.9 19.1l1.4-1.4m11.4-11.4l1.4-1.4" />
    </svg>
  ),
  moon: (
    <svg width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" d="M21 12.8A9 9 0 1111.2 3a7 7 0 009.8 9.8z" />
    </svg>
  ),
  gear: (
    <svg width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
      <circle cx="12" cy="12" r="3" />
      <path strokeLinecap="round" strokeLinejoin="round" d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 11-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 11-4 0v-.09a1.65 1.65 0 00-1-1.51 1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 11-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 110-4h.09a1.65 1.65 0 001.51-1 1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 112.83-2.83l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 114 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 112.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 110 4h-.09a1.65 1.65 0 00-1.51 1z" />
    </svg>
  ),
  disconnect: (
    <svg width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
      <path strokeLinecap="round" strokeLinejoin="round" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
    </svg>
  )
};

export function DashboardHeader({ showSettings, onToggleSettings, activeTab, onChangeTab }: DashboardHeaderProps) {
  const [phone, setPhone] = useState<string | null>(null);
  const [connStatus, setConnStatus] = useState<'disconnected' | 'qr' | 'connecting' | 'connected'>('connecting');
  const [loading, setLoading] = useState(false);
  const [confirmStep, setConfirmStep] = useState(false);
  const [globalModeLoading, setGlobalModeLoading] = useState(false);
  const [showGlobalMenu, setShowGlobalMenu] = useState(false);
  const globalMenuRef = useRef<HTMLDivElement>(null);

  const [theme, setTheme] = useState<'dark' | 'light'>('dark');

  useEffect(() => {
    const savedTheme = localStorage.getItem('theme') as 'dark' | 'light' | null;
    if (savedTheme) {
      setTheme(savedTheme);
      if (savedTheme === 'light') {
        document.documentElement.classList.add('light');
        document.documentElement.classList.remove('dark');
      } else {
        document.documentElement.classList.add('dark');
        document.documentElement.classList.remove('light');
      }
    }
  }, []);

  const toggleTheme = () => {
    const newTheme = theme === 'dark' ? 'light' : 'dark';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
    if (newTheme === 'light') {
      document.documentElement.classList.add('light');
      document.documentElement.classList.remove('dark');
    } else {
      document.documentElement.classList.add('dark');
      document.documentElement.classList.remove('light');
    }
  };

  // Close global menu on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (globalMenuRef.current && !globalMenuRef.current.contains(e.target as Node)) {
        setShowGlobalMenu(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const handleGlobalMode = async (mode: 'AI' | 'HUMAN') => {
    setGlobalModeLoading(true);
    setShowGlobalMenu(false);
    try {
      await fetch('/api/mode/global', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mode }),
      });
    } catch (err) {
      console.error('Error cambiando modo global:', err);
    } finally {
      setGlobalModeLoading(false);
    }
  };

  useEffect(() => {
    const fetchStatus = async () => {
      try {
        const res = await fetch('/api/connection/status');
        const data = await res.json();
        setConnStatus(data.status);
        if (data.phone) {
          setPhone(data.phone);
        } else {
          setPhone(null);
        }
      } catch (err) {
        console.error('Error fetching connection status:', err);
      }
    };
    fetchStatus();
    const interval = setInterval(fetchStatus, 5000);
    return () => clearInterval(interval);
  }, []);

  const handleDisconnect = async () => {
    if (!confirmStep) {
      setConfirmStep(true);
      setTimeout(() => setConfirmStep(false), 3000);
      return;
    }

    setLoading(true);
    try {
      const res = await fetch('/api/connection/disconnect', { method: 'POST' });
      if (res.ok) {
        window.location.reload();
      }
    } catch (err) {
      console.error('Error en desconexión:', err);
    } finally {
      setLoading(false);
      setConfirmStep(false);
    }
  };

  return (
    <header className="dash-header">
      <div className="brand">
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <img 
            src={theme === 'dark' ? '/logo_reservame_white.png' : '/logo_reservame_dark.png'} 
            alt="Reservame" 
            style={{ height: '38px', width: 'auto' }} 
          />
        </div>
        <div style={{ marginLeft: '14px', borderLeft: '1px solid var(--border-strong)', paddingLeft: '14px', display: 'flex', alignItems: 'center', height: '26px' }}>
          <span style={{ fontSize: '0.68rem', color: 'var(--text-muted)', fontWeight: 600, letterSpacing: '0.08em' }}>Command Center</span>
        </div>
      </div>

      <div className="header-tabs" style={{ display: 'flex', gap: '4px', background: 'var(--panel-bg)', padding: '4px', borderRadius: '8px', border: '1px solid var(--border-strong)', marginLeft: '24px' }}>
        <button
          type="button"
          onClick={() => onChangeTab('chats')}
          style={{
            padding: '6px 18px',
            borderRadius: '6px',
            fontSize: '0.8rem',
            fontWeight: 600,
            border: 'none',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            gap: '6px',
            background: activeTab === 'chats' ? 'var(--bg)' : 'transparent',
            color: activeTab === 'chats' ? 'var(--accent)' : 'var(--text-muted)',
            boxShadow: activeTab === 'chats' ? 'var(--shadow-sm)' : 'none',
            transition: 'all 0.2s ease'
          }}
        >
          💬 Chats
        </button>
        <button
          type="button"
          onClick={() => onChangeTab('leads')}
          style={{
            padding: '6px 18px',
            borderRadius: '6px',
            fontSize: '0.8rem',
            fontWeight: 600,
            border: 'none',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            gap: '6px',
            background: activeTab === 'leads' ? 'var(--bg)' : 'transparent',
            color: activeTab === 'leads' ? 'var(--accent)' : 'var(--text-muted)',
            boxShadow: activeTab === 'leads' ? 'var(--shadow-sm)' : 'none',
            transition: 'all 0.2s ease'
          }}
        >
          💼 Prospectos
        </button>
      </div>

      <div className="live-status">
        <span
          className="live-dot"
          style={{
            background:
              connStatus === 'connected' ? 'var(--accent)' :
              connStatus === 'qr' ? '#f59e0b' :
              connStatus === 'connecting' ? '#38bdf8' : 'var(--rose)',
          }}
        />
        <span>
          {connStatus === 'connected' && phone ? (
            <>En línea &middot; <strong>{phone}</strong></>
          ) : connStatus === 'qr' ? (
            <span style={{ color: '#f59e0b', fontWeight: 600 }}>⚠ Escanea el QR</span>
          ) : connStatus === 'connecting' ? (
            <span style={{ color: '#38bdf8' }}>Conectando…</span>
          ) : (
            <span style={{ color: 'var(--rose)', fontWeight: 600 }}>Desconectado</span>
          )}
        </span>
      </div>

      <div className="header-actions">
        {/* Global Mode Toggle Dropdown (adapted to Epic styles) */}
        <div style={{ position: 'relative' }} ref={globalMenuRef}>
          <button
            type="button"
            onClick={() => setShowGlobalMenu((v) => !v)}
            disabled={globalModeLoading}
            className={`icon-btn ${showGlobalMenu ? 'active' : ''}`}
            title="Cambiar modo global"
            style={showGlobalMenu ? { background: 'var(--accent-soft)', color: 'var(--accent)', borderColor: 'var(--accent-border)' } : {}}
          >
            {globalModeLoading ? (
              <span style={{ fontSize: '10px' }}>⌛</span>
            ) : (
              <svg width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <circle cx="12" cy="12" r="10" />
                <path strokeLinecap="round" d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z" />
                <path strokeLinecap="round" d="M2 12h20" />
              </svg>
            )}
          </button>

          {showGlobalMenu && (
            <div
              className="panel"
              style={{
                position: 'absolute',
                right: 0,
                top: 'calc(100% + 8px)',
                width: '220px',
                padding: '8px',
                borderRadius: 'var(--radius)',
                boxShadow: 'var(--shadow)',
                zIndex: 50
              }}
            >
              <p style={{ fontSize: '0.65rem', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-muted)', padding: '4px 8px 8px' }}>
                Cambiar TODAS a:
              </p>
              <button
                onClick={() => handleGlobalMode('AI')}
                style={{
                  width: '100%',
                  textAlign: 'left',
                  padding: '10px',
                  borderRadius: 'var(--radius-sm)',
                  fontSize: '0.8rem',
                  fontWeight: 600,
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  background: 'transparent',
                  border: 'none',
                  color: 'var(--accent)',
                  cursor: 'pointer'
                }}
                onMouseOver={(e) => e.currentTarget.style.background = 'var(--accent-soft)'}
                onMouseOut={(e) => e.currentTarget.style.background = 'transparent'}
              >
                🤖 Modo IA
              </button>
              <button
                onClick={() => handleGlobalMode('HUMAN')}
                style={{
                  width: '100%',
                  textAlign: 'left',
                  padding: '10px',
                  borderRadius: 'var(--radius-sm)',
                  fontSize: '0.8rem',
                  fontWeight: 600,
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  background: 'transparent',
                  border: 'none',
                  color: 'var(--violet)',
                  cursor: 'pointer',
                  marginTop: '4px'
                }}
                onMouseOver={(e) => e.currentTarget.style.background = 'var(--violet-soft)'}
                onMouseOut={(e) => e.currentTarget.style.background = 'transparent'}
              >
                👤 Modo Humano
              </button>
            </div>
          )}
        </div>

        <button type="button" className="icon-btn" onClick={toggleTheme} title="Cambiar tema">
          {theme === 'dark' ? ICONS.sun : ICONS.moon}
        </button>
        <button
          type="button"
          className={`icon-btn ${activeTab === 'settings' ? 'active' : ''}`}
          onClick={() => onChangeTab('settings')}
          title="Configuración"
          style={activeTab === 'settings' ? { background: 'var(--accent-soft)', color: 'var(--accent)', borderColor: 'var(--accent-border)' } : {}}
        >
          {ICONS.gear}
        </button>
        <button
          type="button"
          className="icon-btn"
          onClick={handleDisconnect}
          disabled={loading}
          title={confirmStep ? 'Haz clic otra vez para confirmar' : 'Desconectar WhatsApp'}
          style={
            confirmStep
              ? { background: 'rgba(241,100,124,0.15)', color: 'var(--rose)', borderColor: 'rgba(241,100,124,0.4)', width: 'auto', padding: '0 12px', fontSize: '0.72rem', fontWeight: 700, gap: '6px', display: 'flex', alignItems: 'center' }
              : {}
          }
        >
          {loading ? (
            <div className="spinner-epic" style={{ width: '14px', height: '14px', borderWidth: '2px' }} />
          ) : confirmStep ? (
            <>
              <svg width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
              </svg>
              ¿Confirmar?
            </>
          ) : ICONS.disconnect}
        </button>
      </div>
    </header>
  );
}
