import type { ApiSettings } from "../../types";
import Card from "../../components/Card";
import Button from "../../components/Button";
import DismissibleAlert from "../../components/DismissibleAlert";
import PageTitle from "../../components/PageTitle";
import VersionLine from "./components/VersionLine";
import LoadingFrame from "../../components/LoadingFrame";
import { useCampaignWorkspaceData } from "./hooks/useCampaignWorkspaceData";
import { asRecord, 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>
          <VersionLine version={version} versions={data.versions} loadedAt={version?.updated_at} />
        </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 && <DismissibleAlert tone="danger" resetKey={error} floating>{error}</DismissibleAlert>}
      <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>
  );
}
