import type { ApiSettings } from "../../types";
import Card from "../../components/Card";
import Button from "../../components/Button";
import PageTitle from "../../components/PageTitle";
import LoadingFrame from "../../components/LoadingFrame";
import { useCampaignWorkspaceData } from "./hooks/useCampaignWorkspaceData";
import { asRecord, formatDateTime, getCampaignJson } from "./utils/campaignView";
import { downloadJson, safeFileStem } from "./utils/draftEditor";

export default function CampaignJsonView({ settings, campaignId }: { settings: ApiSettings; campaignId: string }) {
  const { data, loading, error, reload } = useCampaignWorkspaceData(settings, campaignId);
  const version = data.currentVersion;
  const campaignJson = getCampaignJson(version);
  const campaign = asRecord(campaignJson.campaign);
  const filename = `${safeFileStem(String(campaign.id || data.campaign?.external_id || campaignId))}.json`;

  return (
    <div className="content-pad workspace-data-page">
      <div className="page-heading split workspace-heading">
        <div>
          <PageTitle loading={loading}>JSON</PageTitle>
          <p className="mono-small">Version {version ? `#${version.version_number}` : "—"} · Loaded {formatDateTime(version?.updated_at)}</p>
        </div>
        <div className="button-row compact-actions">
          <Button onClick={reload} disabled={loading}>Reload</Button>
          <Button onClick={() => downloadJson(filename, campaignJson)} disabled={!version}>Download JSON</Button>
        </div>
      </div>
      {error && <div className="alert danger">{error}</div>}
      <LoadingFrame loading={loading} label="Loading JSON…">
      <Card>
        {!loading || version ? <pre className="code-panel">{JSON.stringify(campaignJson, null, 2)}</pre> : <pre className="code-panel">{"{}"}</pre>}
      </Card>
      </LoadingFrame>
    </div>
  );
}
