'use client';

import { useState, useEffect, useCallback } from 'react';
import { Plus, Trash2, Pencil, Server, Check, X, Bot, Wifi, WifiOff } from 'lucide-react';
import { toast } from 'sonner';
import { listSipLines, createSipLine, updateSipLine, deleteSipLine } from '@client/api/telephone';
import { listAgents } from '@client/api/ai-agents';
import { useLanguage } from '@client/contexts/LanguageContext';
import type { SipLine } from '@client/api/telephone';
import type { AiAgent } from '@client/api/ai-agents';

const STATUS_STYLE: Record<string, { bg: string; text: string; label: string }> = {
  registered: { bg: 'hsl(var(--success-bg))', text: 'hsl(var(--success))', label: 'Registered' },
  unregistered: { bg: 'hsl(var(--danger-bg))', text: 'hsl(var(--danger))', label: 'Unregistered' },
  unknown: { bg: 'hsl(var(--muted))', text: 'hsl(var(--muted-foreground))', label: 'Unknown' },
};

const COMING_SOON = true;

export default function SipTab() {
  const { t } = useLanguage();
  const [lines, setLines] = useState<SipLine[]>([]);
  const [agents, setAgents] = useState<AiAgent[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAdd, setShowAdd] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({ display_name: '', sip_server: '', sip_username: '', sip_password: '', outbound_proxy: '', assigned_agent_id: '' });

  const fetchData = useCallback(async () => {
    if (COMING_SOON) { setLoading(false); return; }
    setLoading(true);
    try {
      const [sipRes, agentRes] = await Promise.all([listSipLines(), listAgents()]);
      setLines(sipRes.lines || []);
      setAgents(agentRes.agents || []);
    } catch (err: unknown) {
      toast.error(t('telephone.failedToLoad', 'Failed to load: {{error}}', { error: err instanceof Error ? err.message : '' }));
    } finally {
      setLoading(false);
    }
  }, [t]);

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

  const resetForm = () => setForm({ display_name: '', sip_server: '', sip_username: '', sip_password: '', outbound_proxy: '', assigned_agent_id: '' });

  const startEdit = (line: SipLine) => {
    const config = typeof line.sip_config === 'string' ? JSON.parse(line.sip_config) : line.sip_config || {};
    setEditingId(line.id);
    setForm({
      display_name: line.display_name || '',
      sip_server: config.sip_server || '',
      sip_username: config.sip_username || '',
      sip_password: '',
      outbound_proxy: config.outbound_proxy || '',
      assigned_agent_id: line.assigned_agent_id || '',
    });
    setShowAdd(false);
  };

  const handleCreate = async () => {
    if (!form.display_name.trim() || !form.sip_server.trim() || !form.sip_username.trim()) {
      toast.error(t('telephone.sipFormRequired', 'Display name, SIP server, and username are required'));
      return;
    }
    setSaving(true);
    try {
      const res = await createSipLine({
        display_name: form.display_name,
        sip_server: form.sip_server,
        sip_username: form.sip_username,
        sip_password: form.sip_password,
        outbound_proxy: form.outbound_proxy || undefined,
        assigned_agent_id: form.assigned_agent_id || undefined,
      });
      setLines(prev => [res.line, ...prev]);
      resetForm();
      setShowAdd(false);
      toast.success(t('telephone.sipLineCreated', 'SIP line created'));
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t('telephone.createFailed', 'Create failed'));
    } finally {
      setSaving(false);
    }
  };

  const handleUpdate = async () => {
    if (!editingId) return;
    setSaving(true);
    try {
      const data: Record<string, unknown> = {};
      if (form.display_name.trim()) data.display_name = form.display_name.trim();
      if (form.sip_server.trim()) data.sip_server = form.sip_server.trim();
      if (form.sip_username.trim()) data.sip_username = form.sip_username.trim();
      if (form.sip_password) data.sip_password = form.sip_password;
      if (form.outbound_proxy !== undefined) data.outbound_proxy = form.outbound_proxy.trim();
      data.assigned_agent_id = form.assigned_agent_id || null;

      const res = await updateSipLine(editingId, data);
      setLines(prev => prev.map(l => l.id === editingId ? res.line : l));
      setEditingId(null);
      resetForm();
      toast.success(t('telephone.sipLineUpdated', 'SIP line updated'));
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t('telephone.updateFailed', 'Update failed'));
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteSipLine(id);
      setLines(prev => prev.filter(l => l.id !== id));
      toast.success(t('telephone.sipLineDeleted', 'SIP line deleted'));
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t('telephone.deleteFailed', 'Delete failed'));
    }
  };

  if (COMING_SOON) {
    return (
      <div className="flex flex-col items-center justify-center py-20 px-6 text-center">
        <div className="w-16 h-16 rounded-2xl flex items-center justify-center mb-5"
          style={{ backgroundColor: 'hsl(25 95% 53% / 0.12)', border: '1.5px solid hsl(25 95% 53% / 0.25)' }}>
          <Server size={28} style={{ color: 'hsl(25 95% 53%)' }} />
        </div>

        <span className="inline-block text-xs font-bold px-3 py-1 rounded-full mb-4"
          style={{ backgroundColor: 'hsl(25 95% 53%)', color: 'white' }}>
          {t('telephone.soon', 'Coming Soon')}
        </span>

        <h2 className="text-xl font-bold mb-3" style={{ color: 'hsl(var(--foreground))' }}>
          {t('telephone.sipLinesComingSoon', 'SIP Lines — Coming Soon')}
        </h2>

        <p className="text-sm leading-relaxed max-w-md mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('telephone.sipComingSoonDesc', 'Direct SIP trunk integration is under active development. You will be able to connect your existing PBX or VoIP infrastructure, register SIP trunks, assign AI agents per DID, and monitor registration status in real time.')}
        </p>

        <p className="text-xs mb-8" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('telephone.sipContactSupport', 'Contact your account manager or email support@restroagent.com to be notified when SIP Lines become available.')}
        </p>

        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 w-full max-w-lg">
          {[
            { title: t('telephone.sipTrunkReg', 'SIP Trunk Registration'), desc: t('telephone.sipTrunkRegDesc', 'Connect any SIP-compatible PBX or carrier') },
            { title: t('telephone.perDidRouting', 'Per-DID Agent Routing'), desc: t('telephone.perDidRoutingDesc', 'Route each number to a different AI agent') },
            { title: t('telephone.liveMonitoring', 'Live Status Monitoring'), desc: t('telephone.liveMonitoringDesc', 'See registration state and call activity') },
          ].map(f => (
            <div key={f.title} className="card p-4 text-left">
              <p className="text-xs font-semibold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{f.title}</p>
              <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{f.desc}</p>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="space-y-4">
        {[1, 2].map(i => (
          <div key={i} className="card p-5 animate-pulse">
            <div className="h-4 rounded w-1/3 mb-3" style={{ backgroundColor: 'hsl(var(--muted))' }} />
            <div className="h-3 rounded w-2/3" style={{ backgroundColor: 'hsl(var(--muted))' }} />
          </div>
        ))}
      </div>
    );
  }

  const isFormMode = showAdd || editingId !== null;

  return (
    <div className="space-y-5">
      <div className="flex justify-between items-center">
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {t('telephone.sipDesc', 'Connect existing PBX or VoIP infrastructure via SIP.')}
        </p>
        {!isFormMode && (
          <button className="btn-primary text-sm" onClick={() => { resetForm(); setShowAdd(true); setEditingId(null); }}>
            <Plus size={15} /> {t('telephone.addSipLine', 'Add SIP Line')}
          </button>
        )}
      </div>

      {isFormMode && (
        <div className="card p-5 space-y-3" style={{ borderColor: 'hsl(var(--primary))' }}>
          <h3 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>
            {editingId ? t('telephone.editSipLine', 'Edit SIP Line') : t('telephone.newSipLine', 'New SIP Line')}
          </h3>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div>
              <label className="label-base">{t('telephone.sipDisplayName', 'Display Name *')}</label>
              <input className="input-base" placeholder={t('telephone.sipDisplayNamePlaceholder', 'e.g. Main Line')} value={form.display_name}
                onChange={e => setForm(f => ({ ...f, display_name: e.target.value }))} />
            </div>
            <div>
              <label className="label-base">{t('telephone.sipServer', 'SIP Server / Domain *')}</label>
              <input className="input-base" placeholder={t('telephone.sipServerPlaceholder', 'sip.provider.com')} value={form.sip_server}
                onChange={e => setForm(f => ({ ...f, sip_server: e.target.value }))} />
            </div>
            <div>
              <label className="label-base">{t('telephone.sipUsername', 'SIP Username *')}</label>
              <input className="input-base" placeholder={t('telephone.sipUsernamePlaceholder', 'user123')} value={form.sip_username}
                onChange={e => setForm(f => ({ ...f, sip_username: e.target.value }))} />
            </div>
            <div>
              <label className="label-base">{t('telephone.sipPassword', 'SIP Password')}</label>
              <input className="input-base" type="password" placeholder={editingId ? t('telephone.sipPasswordKeep', 'Leave blank to keep') : t('telephone.sipPasswordPlaceholder', 'Password')}
                value={form.sip_password} onChange={e => setForm(f => ({ ...f, sip_password: e.target.value }))} />
            </div>
            <div>
              <label className="label-base">{t('telephone.sipOutboundProxy', 'Outbound Proxy (Optional)')}</label>
              <input className="input-base" placeholder={t('telephone.sipProxyPlaceholder', 'proxy.provider.com:5060')} value={form.outbound_proxy}
                onChange={e => setForm(f => ({ ...f, outbound_proxy: e.target.value }))} />
            </div>
            <div>
              <label className="label-base">{t('telephone.assignToAgent', 'Assign to Agent')}</label>
              <select className="input-base" value={form.assigned_agent_id}
                onChange={e => setForm(f => ({ ...f, assigned_agent_id: e.target.value }))}>
                <option value="">{t('telephone.noAgentAssigned', 'No agent assigned')}</option>
                {agents.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
              </select>
            </div>
          </div>
          <div className="flex gap-2 pt-1">
            <button className="btn-primary text-sm flex-1" onClick={editingId ? handleUpdate : handleCreate} disabled={saving}>
              <Check size={14} /> {saving ? t('telephone.saving', 'Saving...') : editingId ? t('telephone.update', 'Update') : t('telephone.create', 'Create')}
            </button>
            <button className="btn-secondary text-sm" onClick={() => { setShowAdd(false); setEditingId(null); resetForm(); }}>
              <X size={14} /> {t('telephone.cancel', 'Cancel')}
            </button>
          </div>
        </div>
      )}

      {lines.length === 0 && !isFormMode ? (
        <div className="text-center py-12 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <Server size={32} className="mx-auto mb-2 opacity-30" />
          <p className="font-medium">{t('telephone.noSipLines', 'No SIP lines configured')}</p>
          <p className="text-xs mt-1">{t('telephone.noSipLinesDesc', 'Add your first SIP line to connect your PBX system.')}</p>
        </div>
      ) : (
        <div className="space-y-3">
          {lines.map(line => {
            const config = typeof line.sip_config === 'string' ? JSON.parse(line.sip_config) : line.sip_config || {};
            const status = config.registration_status || 'unknown';
            const statusStyle = STATUS_STYLE[status] || STATUS_STYLE.unknown;

            return (
              <div key={line.id} className="card p-4 flex flex-col sm:flex-row sm:items-center gap-3">
                <div className="flex items-center gap-3 flex-1 min-w-0">
                  <div className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0"
                    style={{ backgroundColor: statusStyle.bg }}>
                    {status === 'registered' ? <Wifi size={16} style={{ color: statusStyle.text }} /> : <WifiOff size={16} style={{ color: statusStyle.text }} />}
                  </div>
                  <div className="min-w-0">
                    <div className="flex items-center gap-2">
                      <p className="font-medium text-sm truncate" style={{ color: 'hsl(var(--foreground))' }}>
                        {line.display_name || config.sip_username || t('telephone.sipLine', 'SIP Line')}
                      </p>
                      <span className="text-xs px-1.5 py-0.5 rounded-full font-medium"
                        style={{ backgroundColor: statusStyle.bg, color: statusStyle.text }}>
                        {t(`telephone.statusLabel.${status}`, statusStyle.label)}
                      </span>
                    </div>
                    <p className="text-xs truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {config.sip_username}@{config.sip_server}
                    </p>
                  </div>
                </div>

                <div className="flex items-center gap-2 shrink-0">
                  {line.assigned_agent_name && (
                    <span className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded-lg"
                      style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground))' }}>
                      <Bot size={11} /> {line.assigned_agent_name}
                    </span>
                  )}
                  <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--primary))' }}
                    onClick={() => startEdit(line)} title={t('telephone.edit', 'Edit')}>
                    <Pencil size={14} />
                  </button>
                  <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }}
                    onClick={() => handleDelete(line.id)} title={t('telephone.delete', 'Delete')}>
                    <Trash2 size={14} />
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
