import { api } from '@/lib/api';
import { Card, PageHeader, Pill } from '@/components/ui';
import { CodeIcon, KeyIcon, SendIcon } from '@/components/Icons';
import { RotateSecretForm, WebhookUrlForm } from '@/components/WebhookForms';

type I = { entitled: boolean; webhookUrl: string | null; hasSecret: boolean; signatureHeader: string; deliveries30d: Record<string, number> };

const SAMPLE = `{
  "type": "lead.routed",
  "lead": { "id": "3a79e2f235638fc7", "name": "…", "email": "…", "phone": "…",
            "city": "New York", "practiceArea": "Divorce", "description": "…",
            "createdAt": "2026-10-04T10:30:00.000Z" },
  "lawyerId": 123
}`;

const VERIFY = `// Node.js — verify before trusting the body
const [t, v1] = header.split(',').map((p) => p.split('=')[1]);
const expected = crypto.createHmac('sha256', SECRET).update(\`\${t}.\${rawBody}\`).digest('hex');
const ok = crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1))
  && Math.abs(Date.now() / 1000 - Number(t)) < 300;`;

export default async function Integrations() {
  const d = await api<I>('/firm/integrations');
  return (
    <>
      <PageHeader
        title="Integrations"
        icon={<SendIcon className="h-5 w-5" />}
        description="Send each new enquiry to your CRM or intake system as a signed webhook, in addition to this dashboard. Failed deliveries are retried up to 5 times."
      />
      {!d.entitled && (
        <p className="mb-6 rounded-lg border border-brass/40 bg-brass-soft px-4 py-3 text-sm text-ink-2">
          Lead webhooks are part of the <strong>Firm</strong> plan. Without it, enquiries are delivered to this dashboard (nothing is lost).{' '}
          <a href="/portal/billing" className="link">
            See plans
          </a>
        </p>
      )}
      <div className="grid gap-6 xl:grid-cols-2">
        <div className="space-y-6">
          <Card title="Lead webhook" icon={<SendIcon className="h-4 w-4" />}>
            {d.entitled || d.webhookUrl ? <WebhookUrlForm current={d.webhookUrl} /> : <p className="p-5 text-sm text-muted">Available on the Firm plan.</p>}
            <div className="flex flex-wrap gap-2 border-t border-rule px-5 py-3 text-xs">
              <span className="text-muted">Last 30 days:</span>
              {Object.keys(d.deliveries30d).length ? Object.entries(d.deliveries30d).map(([s, n]) => <Pill key={s} value={`${s} ${n}`} />) : <span className="text-muted">no webhook deliveries</span>}
            </div>
          </Card>
          <Card title="Signing secret" icon={<KeyIcon className="h-4 w-4" />}>
            {d.entitled ? <RotateSecretForm hasSecret={d.hasSecret} /> : <p className="p-5 text-sm text-muted">Available on the Firm plan.</p>}
          </Card>
        </div>
        <Card title="Receiving the webhook" icon={<CodeIcon className="h-4 w-4" />}>
          <div className="space-y-3 p-5 text-sm">
            <p>
              We <code>POST</code> JSON with the header <code>{d.signatureHeader}: t=&lt;unix time&gt;,v1=&lt;hex HMAC-SHA256&gt;</code>. The signature covers <code>t + &quot;.&quot; + raw body</code>. Answer with any 2xx status.
            </p>
            <pre className="overflow-x-auto rounded-lg bg-sunken p-3 text-xs">{SAMPLE}</pre>
            <pre className="overflow-x-auto rounded-lg bg-sunken p-3 text-xs">{VERIFY}</pre>
            <p className="text-xs text-muted">The payload contains client contact details. Store it securely and only for answering the enquiry.</p>
          </div>
        </Card>
      </div>
    </>
  );
}
