'use client';

/**
 * Jambonz integration settings page.
 *
 * Surfaces the per-restaurant jambonz credentials backing the SIP add-on
 * (provider_name='jambonz' in restaurant_api_keys). When no row exists the
 * platform env vars are used; that fallback state is shown so operators
 * understand which credentials are live.
 *
 * Hidden entirely when FEATURE_SIP_ENABLED is off.
 */

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Save, Trash2, Loader, CheckCircle, AlertCircle, KeyRound } from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import {
  getSipFeature,
  getJambonzCredentials,
  saveJambonzCredentials,
  deleteJambonzCredentials,
  type JambonzCredentialsView,
} from '@client/api/sip';

export default function JambonzSettingsPage() {
  usePageHeader('jambonz integration', 'API credentials for the SIP-trunk add-on');
  const router = useRouter();
  const [featureChecked, setFeatureChecked] = useState(false);
  const [featureEnabled, setFeatureEnabled] = useState(false);
  const [view, setView] = useState<JambonzCredentialsView | null>(null);
  const [form, setForm] = useState({ api_key: '', base_url: '', account_sid: '', webhook_secret: '' });
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [savedAt, setSavedAt] = useState<number | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    getSipFeature().then(s => { setFeatureEnabled(s.enabled); setFeatureChecked(true); });
  }, []);
  useEffect(() => {
    if (featureChecked && !featureEnabled) router.replace('/ai-agent-config/phone-numbers');
  }, [featureChecked, featureEnabled, router]);

  useEffect(() => {
    if (!featureEnabled) return;
    getJambonzCredentials()
      .then(v => { setView(v); setForm({ api_key: '', base_url: v.base_url, account_sid: v.account_sid, webhook_secret: '' }); })
      .catch(e => setError(e instanceof Error ? e.message : 'Failed to load credentials'));
  }, [featureEnabled]);

  if (!featureChecked || !featureEnabled) return null;

  async function onSave(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (!view?.configured && !form.api_key.trim()) {
      setError('API key is required');
      return;
    }
    if (!form.base_url.trim()) { setError('Base URL is required'); return; }
    if (!form.account_sid.trim()) { setError('Account SID is required'); return; }
    setSaving(true);
    try {
      // Omit api_key/webhook_secret when blank so the backend keeps saved values.
      const payload: Parameters<typeof saveJambonzCredentials>[0] = {
        base_url: form.base_url,
        account_sid: form.account_sid,
      };
      if (form.api_key.trim()) payload.api_key = form.api_key.trim();
      if (form.webhook_secret.trim()) payload.webhook_secret = form.webhook_secret.trim();
      await saveJambonzCredentials(payload);
      setSavedAt(Date.now());
      const fresh = await getJambonzCredentials();
      setView(fresh);
      setForm(f => ({ ...f, api_key: '', webhook_secret: '' }));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Save failed');
    } finally {
      setSaving(false);
    }
  }

  async function onDelete() {
    if (!confirm('Remove the saved jambonz credentials? The platform env fallback will be used until new credentials are saved.')) return;
    setDeleting(true);
    try {
      await deleteJambonzCredentials();
      const fresh = await getJambonzCredentials();
      setView(fresh);
      setForm({ api_key: '', base_url: '', account_sid: '', webhook_secret: '' });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Delete failed');
    } finally {
      setDeleting(false);
    }
  }

  const envFallback = view?.env_fallback;
  const hasFullEnvFallback = envFallback?.base_url && envFallback?.api_key && envFallback?.account_sid;

  return (
    <div className="max-w-2xl mx-auto p-6 space-y-6">
      <Link href="/ai-agent-config/phone-numbers" className="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900">
        <ArrowLeft size={16} /> Back to phone numbers
      </Link>

      <div className="bg-white rounded-xl border border-gray-200 p-6 space-y-4">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-indigo-50 text-indigo-600"><KeyRound size={20} /></div>
          <div>
            <h2 className="text-lg font-semibold text-gray-900">jambonz credentials</h2>
            <p className="text-sm text-gray-600">These power every SIP carrier, application and call this restaurant provisions.</p>
          </div>
        </div>

        <div className="rounded-lg bg-gray-50 border border-gray-200 p-4 text-sm text-gray-700 space-y-1">
          <div><span className="font-medium">Saved key:</span> {view?.configured ? <code className="font-mono">{view.key_hint}</code> : <span className="text-gray-500">— none —</span>}</div>
          <div><span className="font-medium">Saved base URL:</span> {view?.base_url || <span className="text-gray-500">— none —</span>}</div>
          <div><span className="font-medium">Saved account SID:</span> {view?.account_sid ? <code className="font-mono">{view.account_sid}</code> : <span className="text-gray-500">— none —</span>}</div>
          <div className="pt-2 text-xs text-gray-500">
            Platform env fallback: {hasFullEnvFallback ? <span className="text-green-700 font-medium">complete</span> : <span className="text-amber-700 font-medium">partial — saving credentials below is recommended</span>}
          </div>
        </div>

        <form onSubmit={onSave} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">jambonz base URL</label>
            <input type="url" required placeholder="https://api.jambonz.example.com"
              value={form.base_url}
              onChange={e => setForm(f => ({ ...f, base_url: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"/>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Account SID</label>
            <input type="text" required placeholder="acct-..."
              value={form.account_sid}
              onChange={e => setForm(f => ({ ...f, account_sid: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"/>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">API key {view?.configured && <span className="text-xs text-gray-500">(leave blank to keep saved key)</span>}</label>
            <input type="password" autoComplete="new-password" placeholder={view?.configured ? '•••••••• (unchanged)' : 'jambonz API key'}
              value={form.api_key}
              onChange={e => setForm(f => ({ ...f, api_key: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"/>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Webhook signing secret{' '}
              {view?.webhook_secret_configured
                ? <span className="text-xs text-gray-500">(saved <code className="font-mono">{view.webhook_secret_hint}</code> — leave blank to keep)</span>
                : view?.env_fallback.webhook_secret
                  ? <span className="text-xs text-amber-700">(none saved — falling back to platform env)</span>
                  : <span className="text-xs text-amber-700">(none saved — webhooks will be permissive in dev only)</span>}
            </label>
            <input type="password" autoComplete="new-password" placeholder={view?.webhook_secret_configured ? '•••••••• (unchanged)' : 'jambonz HMAC secret'}
              value={form.webhook_secret}
              onChange={e => setForm(f => ({ ...f, webhook_secret: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"/>
            <p className="mt-1 text-xs text-gray-500">Used to verify the HMAC signature on /api/webhooks/sip/* calls from jambonz.</p>
          </div>

          {error && (
            <div className="flex items-start gap-2 text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg p-3">
              <AlertCircle size={16} className="mt-0.5 flex-shrink-0" /> {error}
            </div>
          )}
          {savedAt && (
            <div className="flex items-center gap-2 text-sm text-green-700 bg-green-50 border border-green-200 rounded-lg p-3">
              <CheckCircle size={16} /> Credentials saved.
            </div>
          )}

          <div className="flex items-center gap-2 pt-2">
            <button type="submit" disabled={saving}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium hover:bg-indigo-700 disabled:opacity-60">
              {saving ? <Loader size={16} className="animate-spin" /> : <Save size={16} />} Save credentials
            </button>
            {view?.configured && (
              <button type="button" onClick={onDelete} disabled={deleting}
                className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-red-200 text-red-700 text-sm font-medium hover:bg-red-50 disabled:opacity-60">
                {deleting ? <Loader size={16} className="animate-spin" /> : <Trash2 size={16} />} Remove
              </button>
            )}
          </div>
        </form>
      </div>
    </div>
  );
}
