import type { ApiSettings } from "../../types";
import { Card } from "@govoplan/core-webui";
import { Button } from "@govoplan/core-webui";
import { DismissibleAlert } from "@govoplan/core-webui";
import { PageTitle } from "@govoplan/core-webui";
import VersionLine from "./components/VersionLine";
import { LoadingFrame } from "@govoplan/core-webui";
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}>i18n:govoplan-campaign.json.031a4e76</PageTitle>
          <VersionLine version={version} versions={data.versions} loadedAt={version?.updated_at} />
        </div>
        <div className="button-row compact-actions">
          <Button onClick={reload} disabled={loading}>i18n:govoplan-campaign.reload.cce71553</Button>
          <Button onClick={() => downloadJson(filename, campaignJson)} disabled={!version}>i18n:govoplan-campaign.download_json.d296a30a</Button>
        </div>
      </div>
      {error && <DismissibleAlert tone="danger" resetKey={error} floating>{error}</DismissibleAlert>}
      <LoadingFrame loading={loading} label="i18n:govoplan-campaign.loading_json.812c7a50">
      <Card>
        {!loading || version ? <pre className="code-panel">{JSON.stringify(campaignJson, null, 2)}</pre> : <pre className="code-panel">{"{}"}</pre>}
      </Card>
      </LoadingFrame>
    </div>);

}