"use client";

import { ActionIcon, Badge, Group, Select, Text, Tooltip } from "@mantine/core";
import { IconArrowLeft, IconRefresh } from "@tabler/icons-react";
import { useState } from "react";
import { Link } from "react-router";
import type { DashboardDetail } from "@/lib/features/dashboard/types";
import DashboardFrame from "../../_components/DashboardFrame";
import classes from "../../_components/dashboard.module.css";

/**
 * Authenticated full-bleed viewer.
 *
 * Chrome is deliberately thin — name, version, back, and (admins only) a
 * version switcher. The dashboard is the content; everything else gets out of
 * the way. There is intentionally no print or export control: see the honesty
 * note in dashboard.module.css about how soft those protections are.
 */
const DashboardViewer: React.FC<{ detail: DashboardDetail }> = ({ detail }) => {
  const { dashboard, versions, isDashboardAdmin } = detail;

  const [versionId, setVersionId] = useState<string>(
    dashboard.current_version_id ?? "",
  );
  const [nonce, setNonce] = useState(0);

  const isCurrent = versionId === dashboard.current_version_id;
  const active = versions.find((v) => v.id === versionId);

  /*
   * ?v= is honoured by the backend for dashboard admins ONLY — a regular
   * viewer always gets the current published version no matter what they put
   * in the URL. We don't re-implement that rule here; we simply don't offer
   * the control to people it wouldn't work for.
   */
  const src = `/api/proxy/v1/admin-console/dashboards/${dashboard.id}/serve/${
    isDashboardAdmin && versionId && !isCurrent ? `?v=${versionId}` : ""
  }`;

  return (
    <div className={classes.viewerShell}>
      <div className={classes.viewerChrome}>
        <Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
          <Tooltip label="Back to dashboard" withArrow>
            <ActionIcon
              component={Link}
              to={`/admin/dashboard/${dashboard.slug}`}
              variant="subtle"
              radius="md"
              aria-label="Back to dashboard"
            >
              <IconArrowLeft size={17} />
            </ActionIcon>
          </Tooltip>
          <Text fw={600} size="sm" truncate>
            {dashboard.name}
          </Text>
          {active && (
            <Badge
              size="xs"
              radius="sm"
              variant="light"
              color={isCurrent ? "teal" : "yellow"}
            >
              v{active.version_number}
              {isCurrent ? " · live" : " · preview"}
            </Badge>
          )}
        </Group>

        <Group gap="xs" wrap="nowrap">
          {/* Admin-only: matches what the backend will actually honour. */}
          {isDashboardAdmin && versions.length > 1 && (
            <Select
              size="xs"
              radius="md"
              w={185}
              value={versionId}
              onChange={(v) =>
                setVersionId(v ?? dashboard.current_version_id ?? "")
              }
              allowDeselect={false}
              aria-label="Preview a version"
              data={versions.map((v) => ({
                value: v.id,
                label:
                  v.id === dashboard.current_version_id
                    ? `v${v.version_number} (live)`
                    : `v${v.version_number}`,
              }))}
            />
          )}
          <Tooltip label="Reload" withArrow>
            <ActionIcon
              variant="subtle"
              radius="md"
              aria-label="Reload dashboard"
              onClick={() => setNonce((n) => n + 1)}
            >
              <IconRefresh size={16} />
            </ActionIcon>
          </Tooltip>
        </Group>
      </div>

      <DashboardFrame
        serveSrc={src}
        mode="authed"
        title={`${dashboard.name} dashboard`}
        reloadKey={`${versionId}:${nonce}`}
      />
    </div>
  );
};

export default DashboardViewer;
