/* Dispatch — Integrations
 * Loaded by index.html after lib.jsx.
 *
 * Replicates the original SlackIntegrationsView: live Slack integration status
 * from fetchSlackIntegrationsStatus() — workspace connection, channels the bot
 * is in, inbox triage volume, trigger reactions, and the slash command.
 * Read-only (behavior changes via the Slack app config / server env). */

function Integrations() {
  const [status, setStatus] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  async function reload() {
    setLoading(true);
    try {
      const r = await api.fetchSlackIntegrationsStatus();
      setStatus(r); setError((r && r.error) || null);
    } catch (e) { setError(e.message || 'Failed to load Slack status'); }
    finally { setLoading(false); }
  }
  useEffect(() => { reload(); }, []);

  const ws = status && status.workspace;
  const channels = (status && status.channels) || [];
  const triggers = (status && status.triggers && status.triggers.reactions) || [];
  const stats = (status && status.inboxStats) || { pending: 0, convertedHelpdesk: 0, sentGithub: 0, dismissed: 0 };
  const configured = !!(status && status.configured);
  const connected = configured && !!ws;
  const kpis = [
    { label: 'Pending', value: stats.pending }, { label: 'Help Desk', value: stats.convertedHelpdesk },
    { label: 'GitHub', value: stats.sentGithub }, { label: 'Dismissed', value: stats.dismissed },
  ];

  return (
    <div className="space-y-4">
      <Card className="border-primary/20 bg-primary/5">
        <CardContent className="pt-6">
          <h2 className="text-2xl font-semibold tracking-tight">Slack workspace : {connected ? 'Connected' : configured ? 'Configured but unreachable' : 'Not configured'}</h2>
          <p className="mt-1 text-sm text-muted-foreground">Live status of the Dispatch ↔ Slack integration. Read-only — change behavior via the Slack app config or server env vars.</p>
        </CardContent>
      </Card>

      {error && <div className="rounded-md border border-amber-300 bg-amber-50 px-4 py-2 text-sm text-amber-800"><strong>Slack API error.</strong> {error}</div>}

      {/* Workspace connection */}
      <Card>
        <CardHeader className="flex-row items-center justify-between gap-2 space-y-0">
          <div><CardTitle>Workspace connection</CardTitle><p className="mt-1 text-sm text-muted-foreground">Bot identity from Slack's auth.test.</p></div>
          <div className="flex items-center gap-2">
            <Badge variant={connected ? 'default' : 'outline'}>{connected ? '● Connected' : configured ? '○ Unreachable' : '○ Not configured'}</Badge>
            <Button variant="outline" size="sm" onClick={reload} disabled={loading}>{loading ? '…' : 'Refresh'}</Button>
          </div>
        </CardHeader>
        <CardContent>
          {!configured ? (
            <div className="text-sm text-muted-foreground">The server has no <code>SLACK_BOT_TOKEN</code> / <code>SLACK_SIGNING_SECRET</code> set. Add them in Render → Environment to enable the integration.</div>
          ) : (
            <div className="flex flex-wrap items-center gap-x-8 gap-y-2 text-sm">
              <div><div className="text-lg font-semibold">{ws?.teamName || '—'}</div><div className="text-xs text-muted-foreground">team id <code>{ws?.teamId || '—'}</code></div></div>
              <div>Bot user <strong>@{ws?.botName || '—'}</strong> <span className="font-mono text-xs text-muted-foreground">{ws?.botUserId || ''}</span></div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Channels */}
      <Card>
        <CardHeader className="flex-row items-center justify-between gap-2 space-y-0">
          <div><CardTitle>Channels the bot is in</CardTitle><p className="mt-1 text-sm text-muted-foreground">Where the bot listens for <code>@dispatch</code> mentions and trigger reactions.</p></div>
          <Badge variant="outline">{channels.length} {channels.length === 1 ? 'channel' : 'channels'}</Badge>
        </CardHeader>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="border-b text-muted-foreground"><tr className="[&>th]:px-4 [&>th]:py-2.5 [&>th]:text-left [&>th]:font-medium"><th>Channel</th><th className="text-right">Members</th><th>Visibility</th><th>ID</th></tr></thead>
            <tbody className="divide-y">
              {loading && channels.length === 0 && <tr><td colSpan="4" className="px-4 py-6 text-center text-muted-foreground">Loading…</td></tr>}
              {!loading && channels.length === 0 && <tr><td colSpan="4" className="px-4 py-6 text-center text-muted-foreground">Bot isn't in any channels. Run <code>/invite @dispatch</code> in a channel.</td></tr>}
              {channels.map(c => (
                <tr key={c.id} className="hover:bg-muted/50">
                  <td className="px-4 py-2.5 font-medium">{c.isPrivate ? '🔒' : '#'} {c.name}</td>
                  <td className="px-4 py-2.5 text-right text-muted-foreground">{c.memberCount != null ? c.memberCount : '—'}</td>
                  <td className="px-4 py-2.5"><Badge variant="outline">{c.isArchived ? 'archived' : c.isPrivate ? 'private' : 'public'}</Badge></td>
                  <td className="px-4 py-2.5 font-mono text-xs text-muted-foreground">{c.id}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      {/* Inbox triage volume */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {kpis.map(k => (
          <Card key={k.label}><CardContent className="pt-5"><div className="text-sm text-muted-foreground">{k.label}</div><div className="mt-1 text-3xl font-semibold tracking-tight">{k.value}</div></CardContent></Card>
        ))}
      </div>

      {/* Trigger reactions + slash command */}
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-sm">Trigger reactions</CardTitle><p className="mt-1 text-xs text-muted-foreground">Emoji that flag a message for the Slack inbox (<code>SLACK_TRIGGER_REACTIONS</code>).</p></CardHeader>
          <CardContent className="flex flex-wrap gap-2">
            {triggers.length === 0 ? <span className="text-sm text-muted-foreground">None configured.</span> : triggers.map(r => <Badge key={r} variant="outline">:{r}:</Badge>)}
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2"><CardTitle className="text-sm">Slash command</CardTitle><p className="mt-1 text-xs text-muted-foreground">Anyone in a channel with the bot can file tickets.</p></CardHeader>
          <CardContent className="flex items-center gap-3 text-sm"><code className="font-semibold">/dispatch</code><span className="text-muted-foreground">Opens a modal to file a Help Desk ticket</span></CardContent>
        </Card>
      </div>
    </div>
  );
}
