"use client";

import { useState } from "react";
import { Button, Card, CardHeader } from "@/components/ui";
import { Field, inputClass } from "@/components/ui/form";
import { StatusLine, useRun } from "@/components/features/accounts/use-run";
import { reviewIntegrationAction, setIntegrationPolicyAction } from "@/lib/actions/integrations";
import { INTEGRATION_TYPES, TYPE_INFO, type IntegrationType } from "@/lib/integrations/schema";
import type { IntegrationRow, SiteIntegrations } from "@/lib/services/integrations";
import { Deliveries, IntegrationStatusBadge } from "./status";

type Pending = IntegrationRow & { siteId: string; siteName: string; organizationName: string };

export function PolicyToggles({ policies }: { policies: Record<IntegrationType, boolean> }) {
  const { pending, msg, run } = useRun();
  return (
    <Card>
      <CardHeader title="Approval rules" description="Choose which integration types need your approval before they start working. Turning a rule off activates the ones already waiting." />
      <ul className="divide-y divide-border">
        {INTEGRATION_TYPES.map((t) => (
          <li key={t} className="flex items-center justify-between gap-3 px-4 py-3">
            <div><p className="text-sm font-medium">{TYPE_INFO[t].label}</p><p className="text-xs text-muted-foreground">{TYPE_INFO[t].description}</p></div>
            <label className="flex items-center gap-2 text-sm"><input type="checkbox" disabled={pending} checked={policies[t]} onChange={(e) => run(() => setIntegrationPolicyAction(t, e.target.checked))} />Needs approval</label>
          </li>
        ))}
      </ul>
      <div className="px-4 pb-3"><StatusLine msg={msg} /></div>
    </Card>
  );
}

export function PendingQueue({ rows }: { rows: Pending[] }) {
  const { pending, msg, errors, run } = useRun();
  const [rejecting, setRejecting] = useState<string | null>(null);
  const [note, setNote] = useState("");
  return (
    <Card>
      <CardHeader title={`Waiting for approval (${rows.length})`} />
      <div className="px-4 pt-2"><StatusLine msg={msg} /></div>
      {rows.length === 0 ? <p className="px-4 py-4 text-sm text-muted-foreground">Nothing is waiting for approval.</p> : (
        <ul className="divide-y divide-border">
          {rows.map((r) => (
            <li key={r.id} className="space-y-2 px-4 py-3">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div><p className="font-medium">{r.name} <span className="text-xs font-normal text-muted-foreground">· {r.typeLabel}</span></p><p className="text-sm text-muted-foreground">{r.siteName} ({r.organizationName})</p><p className="text-sm">{r.summary}</p></div>
                <div className="flex gap-2">
                  <Button disabled={pending} onClick={() => run(() => reviewIntegrationAction(r.id, { decision: "approve", note: "" }))} aria-label={`Approve ${r.name}`}>Approve</Button>
                  <Button variant="secondary" onClick={() => { setRejecting(rejecting === r.id ? null : r.id); setNote(""); }} aria-label={`Reject ${r.name}`}>Reject</Button>
                </div>
              </div>
              {rejecting === r.id ? (
                <form className="flex flex-wrap items-end gap-2" onSubmit={(e) => { e.preventDefault(); run(() => reviewIntegrationAction(r.id, { decision: "reject", note }), () => setRejecting(null)); }}>
                  <Field id={`rj-${r.id}`} label="Reason shown to the admin" error={errors.note} className="min-w-64 flex-1"><input id={`rj-${r.id}`} required minLength={3} maxLength={500} value={note} onChange={(e) => setNote(e.target.value)} className={inputClass} /></Field>
                  <Button type="submit" variant="danger" disabled={pending}>Confirm reject</Button>
                </form>
              ) : null}
            </li>
          ))}
        </ul>
      )}
    </Card>
  );
}

/** Read-only: which website has which integration. No secrets are ever sent here. */
export function WebsiteIntegrations({ sites, websitesWithout }: { sites: SiteIntegrations[]; websitesWithout: number }) {
  return (
    <Card>
      <CardHeader title="Integrations by website" description={websitesWithout ? `${websitesWithout} website${websitesWithout === 1 ? " has" : "s have"} none yet. Admins add integrations from their own dashboard.` : "Admins add integrations from their own dashboard."} />
      {sites.length === 0 ? <p className="px-4 py-4 text-sm text-muted-foreground">No website has added an integration yet.</p> : (
        <div className="divide-y divide-border">
          {sites.map((s) => (
            <details key={s.siteId} className="group">
              <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-4 py-3 text-sm font-medium hover:bg-muted"><span>{s.siteName} <span className="text-xs font-normal text-muted-foreground">· {s.organizationName}</span></span><span className="text-xs font-normal text-muted-foreground">{s.integrations.length} integration{s.integrations.length === 1 ? "" : "s"}</span></summary>
              <ul className="divide-y divide-border border-t border-border">
                {s.integrations.map((r) => (
                  <li key={r.id} className="space-y-1 px-6 py-3">
                    <p className="text-sm font-medium">{r.name} <span className="text-xs font-normal text-muted-foreground">· {r.typeLabel}</span> <IntegrationStatusBadge status={r.status} /></p>
                    <p className="text-sm text-muted-foreground">{r.summary}</p>
                    {r.reviewNote ? <p className="text-xs">Note: {r.reviewNote}</p> : null}
                    {r.type === "webhook" || r.type === "smtp" ? <details><summary className="cursor-pointer text-xs text-muted-foreground">Recent activity</summary><div className="mt-1"><Deliveries rows={r.deliveries} /></div></details> : null}
                  </li>
                ))}
              </ul>
            </details>
          ))}
        </div>
      )}
    </Card>
  );
}
