'use client';

import { useState, useEffect } from 'react';
import { useIsMobile } from '@/lib/useIsMobile';
import { useTranslation } from '@/lib/i18n';
import ApiKeysSection from './ApiKeysSection';
import SkillsSection from './SkillsSection';
import ExportsSection from './ExportsSection';
import LanguageSection from './LanguageSection';
import AgentRuntimeSection from './AgentRuntimeSection';

interface SettingsModalProps {
  open: boolean;
  onClose: () => void;
  workspaceId?: string;
  initialSection?: Section;
}

type Section = 'agent' | 'language' | 'api-keys' | 'skills' | 'exports';

export default function SettingsModal({ open, onClose, workspaceId, initialSection }: SettingsModalProps) {
  const [activeSection, setActiveSection] = useState<Section>(initialSection ?? 'agent');
  const isMobile = useIsMobile();
  const { t } = useTranslation();

  // Update active section when initialSection changes
  useEffect(() => {
    if (initialSection) {
      setActiveSection(initialSection);
    }
  }, [initialSection]);

  if (!open) return null;

  const navItems: { key: Section; label: string; icon: string }[] = [
    { key: 'agent', label: t('settings.navAgentRuntime'), icon: '🤖' },
    { key: 'language', label: t('settings.navLanguage'), icon: '🌐' },
    { key: 'api-keys', label: t('settings.navApiKeys'), icon: '🔑' },
    { key: 'exports', label: t('settings.navExports'), icon: '📦' },
  ];

  // Only show Skills section if workspaceId is provided
  if (workspaceId) {
    navItems.push({ key: 'skills', label: t('settings.navSkillHub'), icon: '🧠' });
  }

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{
          position: 'fixed',
          inset: 0,
          background: 'rgba(0,0,0,0.25)',
          zIndex: 1000,
        }}
      />

      {/* Modal */}
      <div style={{
        position: 'fixed',
        top: isMobile ? 0 : '50%',
        left: isMobile ? 0 : '50%',
        right: isMobile ? 0 : undefined,
        bottom: isMobile ? 0 : undefined,
        transform: isMobile ? 'none' : 'translate(-50%, -50%)',
        background: '#fff',
        borderRadius: isMobile ? '14px 14px 0 0' : '14px',
        boxShadow: '0 8px 40px rgba(0,0,0,0.18)',
        width: isMobile ? '100%' : '920px',
        maxWidth: isMobile ? '100%' : '92vw',
        height: isMobile ? 'auto' : '680px',
        maxHeight: isMobile ? '90vh' : '85vh',
        display: 'flex',
        flexDirection: isMobile ? 'column' : 'row',
        overflow: 'hidden',
        zIndex: 1001,
      }}>
        {/* Nav — sidebar on desktop, top tab bar on mobile */}
        <div style={{
          width: isMobile ? '100%' : '200px',
          flexShrink: 0,
          borderRight: isMobile ? 'none' : '1px solid #f0f0f0',
          borderBottom: isMobile ? '1px solid #f0f0f0' : 'none',
          padding: isMobile ? '8px 12px 0' : '12px 8px',
          overflowY: isMobile ? 'visible' : 'auto',
          overflowX: isMobile ? 'auto' : 'visible',
          background: '#fafafa',
          display: 'flex',
          flexDirection: isMobile ? 'row' : 'column',
          alignItems: isMobile ? 'center' : 'stretch',
          gap: isMobile ? '4px' : 0,
        }}>
          {!isMobile && (
            <div style={{
              fontSize: '11px',
              fontWeight: 600,
              color: '#9ca3af',
              padding: '8px 10px 4px',
              textTransform: 'uppercase',
              letterSpacing: '0.04em',
            }}>
              {t('settings.title')}
            </div>
          )}
          {navItems.map(item => {
            const isActive = activeSection === item.key;
            return (
              <button
                key={item.key}
                onClick={() => setActiveSection(item.key)}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  width: isMobile ? 'auto' : '100%',
                  padding: isMobile ? '6px 12px' : '7px 10px',
                  border: 'none',
                  borderRadius: isMobile ? '6px 6px 0 0' : '6px',
                  borderBottom: isMobile && isActive ? '2px solid #5b5bd6' : isMobile ? '2px solid transparent' : 'none',
                  background: isMobile ? 'transparent' : (isActive ? '#e8e8f0' : 'transparent'),
                  color: isActive ? '#1a1a2e' : '#555',
                  fontWeight: isActive ? 600 : 400,
                  fontSize: '13px',
                  cursor: 'pointer',
                  textAlign: 'left',
                  transition: 'background 0.12s',
                  whiteSpace: 'nowrap',
                }}
                onMouseEnter={e => { if (!isActive && !isMobile) e.currentTarget.style.background = '#eeeeee'; }}
                onMouseLeave={e => { if (!isActive && !isMobile) e.currentTarget.style.background = 'transparent'; }}
              >
                <span style={{ fontSize: '15px', opacity: 0.7 }}>{item.icon}</span>
                {item.label}
              </button>
            );
          })}
        </div>

        {/* Right content */}
        <div style={{
          flex: 1,
          overflowY: 'auto',
          padding: isMobile ? '16px' : '20px 24px',
          position: 'relative',
        }}>
          {/* Close button */}
          <button
            onClick={onClose}
            style={{
              position: 'absolute',
              top: '12px',
              right: '12px',
              background: 'none',
              border: 'none',
              fontSize: '18px',
              color: '#999',
              cursor: 'pointer',
              padding: '2px 7px',
              borderRadius: '6px',
              lineHeight: 1,
            }}
            onMouseEnter={e => (e.currentTarget.style.background = 'rgba(0,0,0,0.05)')}
            onMouseLeave={e => (e.currentTarget.style.background = 'none')}
          >
            ×
          </button>

          {activeSection === 'language' && <LanguageSection />}
          {activeSection === 'agent' && <AgentRuntimeSection />}
          {activeSection === 'api-keys' && <ApiKeysSection />}
          {activeSection === 'skills' && workspaceId && <SkillsSection workspaceId={workspaceId} />}
          {activeSection === 'exports' && <ExportsSection />}
        </div>
      </div>
    </>
  );
}
