'use client';

import { useState } from 'react';
import { Phone, Server } from 'lucide-react';
import { useLanguage } from '@client/contexts/LanguageContext';
import TwilioTab from './TwilioTab';
import SipTab from './SipTab';
import FeatureGuard from '@client/components/FeatureGuard';
import PermissionDenied from '@client/components/ui/PermissionDenied';

type TabKey = 'twilio' | 'sip';

export default function TelephonePage() {
  const { t } = useLanguage();
  const TABS = [
    { key: 'twilio', label: t('telephone.twilio', 'Twilio'), icon: Phone, coming_soon: false },
    { key: 'sip', label: t('telephone.sipLines', 'SIP Lines'), icon: Server, coming_soon: true },
  ] as const;

  const [tab, setTab] = useState<TabKey>('twilio');
  const [forbidden, setForbidden] = useState(false);

  if (forbidden) {
    return (
      <FeatureGuard feature="voice_agent" featureName="Voice Agent">
        <PermissionDenied sectionName="the Telephone section" />
      </FeatureGuard>
    );
  }

  return (
    <FeatureGuard feature="voice_agent" featureName="Voice Agent">
    <div className="p-6 max-w-5xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>{t('telephone.title', 'Telephone')}</h1>
        <p className="text-sm mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('telephone.subtitle', 'Manage voice channels, connect Twilio numbers or SIP trunks to your AI agents.')}
        </p>
      </div>

      <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
        {TABS.map(tabItem => {
          const Icon = tabItem.icon;
          const active = tab === tabItem.key;
          return (
            <button key={tabItem.key}
              onClick={() => setTab(tabItem.key)}
              className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all"
              style={{
                backgroundColor: active ? 'hsl(var(--card))' : 'transparent',
                color: active ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))',
                boxShadow: active ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
              }}>
              <Icon size={15} />
              {tabItem.label}
              {tabItem.coming_soon && (
                <span className="text-[10px] font-bold px-1.5 py-0.5 rounded-full" style={{ backgroundColor: 'hsl(25 95% 53%)', color: 'white', lineHeight: 1 }}>
                  {t('telephone.soon', 'Soon')}
                </span>
              )}
            </button>
          );
        })}
      </div>

      {tab === 'twilio' && <TwilioTab onForbidden={() => setForbidden(true)} />}
      {tab === 'sip' && <SipTab />}
    </div>
    </FeatureGuard>
  );
}
