import Shell from "@/components/Shell";
import { requireSession, asMembershipRow } from "@/lib/session";
import { can } from "@/lib/rbac";
import { getMainWpIntegration } from "@/lib/data/integrations";
import { PageHeader, Card, Badge } from "@/components/ui";
import { saveMainWpIntegrationAction } from "@/lib/actions/integration-actions";

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="bg-bg-card px-4 py-3.5 flex justify-between gap-4">
      <span className="text-[13px] text-text-secondary">{label}</span>
      <span className="text-[13px] font-semibold font-mono">{value}</span>
    </div>
  );
}

export default async function SettingsPage() {
  const session = await requireSession();
  const m = asMembershipRow(session);
  const integration = getMainWpIntegration(session.orgId);
  const config = JSON.parse(integration.config || "{}");

  return (
    <Shell session={session} active="/settings">
      <PageHeader title="Account settings" description="Profile and organization" />
      <div className="flex flex-col gap-px bg-border border border-border rounded-xl overflow-hidden mb-6">
        <Row label="Name" value={session.name} />
        <Row label="Email" value={session.email} />
        <Row label="Organization" value={session.orgName} />
        <Row label="Your role" value={session.role} />
      </div>

      {can.manageIntegrations(m) && (
        <>
          <div className="text-[13px] font-bold mb-3">MainWP integration</div>
          <Card className="mb-2">
            <div className="flex items-center justify-between mb-4">
              <div className="text-sm text-text-secondary max-w-md">
                Connects to the MainWP Dashboard plugin so site status comes from real MainWP
                data. Enter the MainWP hub base URL and a read-only REST API key (consumer key
                + secret) below, then a scheduled sync job pulls each site&apos;s status on a
                regular interval.
                {integration.updated_at
                  ? ` Last checked: ${new Date(integration.updated_at).toLocaleString()}.`
                  : ""}
              </div>
              <Badge
                status={
                  integration.status.startsWith("Configured") || integration.status.startsWith("Connected")
                    ? "ACTIVE"
                    : "Not connected"
                }
              >
                {integration.status}
              </Badge>
            </div>
            <form action={saveMainWpIntegrationAction} className="flex flex-col gap-3.5">
              <div>
                <label className="block text-xs text-text-secondary mb-1.5">
                  MainWP hub base URL
                </label>
                <input
                  name="baseUrl"
                  defaultValue={config.baseUrl ?? ""}
                  placeholder="https://webstation.app/wp-admin"
                  className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-sm font-mono outline-none"
                />
              </div>
              <div>
                <label className="block text-xs text-text-secondary mb-1.5">
                  Application password / consumer key
                </label>
                <input
                  name="consumerKey"
                  type="password"
                  defaultValue={config.consumerKey ?? ""}
                  className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-sm font-mono outline-none"
                />
              </div>
              <div>
                <label className="block text-xs text-text-secondary mb-1.5">
                Consumer secret
                </label>
                  <input
                  name="consumerSecret"
                  type="password"
                  defaultValue={config.consumerSecret ?? ""}
                  className="w-full bg-bg-input border border-border-input rounded-lg px-3 py-2.5 text-sm font-mono outline-none"
                />
              </div>
              <button
                type="submit"
                className="bg-accent text-white font-bold text-sm px-4 py-2 rounded-lg self-start"
              >
                Save
              </button>
            </form>
          </Card>
        </>
      )}
    </Shell>
  );
}
