import Link from "next/link";

import { DataTable } from "@/components/data-table";
import { SectionHeading } from "@/components/section-heading";
import type { DatasetDetail, DatasetRowsResponse, DatasetSummary } from "@/lib/api/types";

export function DatasetBrowser({
  datasets,
  selectedDataset,
  rows,
}: {
  datasets: DatasetSummary[];
  selectedDataset: DatasetDetail | null;
  rows: DatasetRowsResponse | null;
}) {
  return (
    <div className="pageStack">
      <SectionHeading
        kicker="Datasets"
        title="Dataset browser"
        description="Schema, freshness, partitions, and row samples."
      />
      <div className="panelGrid">
        <div className="panel">
          <div className="panelHeader"><h3>Available datasets</h3></div>
          <ul className="datasetList">
            {datasets.map((dataset) => (
              <li key={dataset.id}>
                <Link href={`/datasets?dataset=${dataset.id}`}>{dataset.id}</Link>
                <strong>{dataset.rows}</strong>
              </li>
            ))}
          </ul>
        </div>
        <div className="panel">
          <div className="panelHeader"><h3>{selectedDataset?.name ?? "Dataset detail"}</h3></div>
          <ul className="summaryList">
            <li><span>Primary key</span><strong>{selectedDataset?.primary_key.join(", ") ?? "n/a"}</strong></li>
            <li><span>Partitions</span><strong>{selectedDataset?.partition_columns.join(", ") ?? "n/a"}</strong></li>
            <li><span>Latest ts</span><strong>{selectedDataset?.latest_logical_ts ?? "n/a"}</strong></li>
            <li><span>Columns</span><strong>{selectedDataset?.schema_columns.length ?? 0}</strong></li>
          </ul>
        </div>
      </div>
      <div className="panel">
        <div className="panelHeader"><h3>Sample rows</h3></div>
        <DataTable
          columns={rows?.rows[0] ? Object.keys(rows.rows[0]).slice(0, 8) : ["status"]}
          rows={rows?.rows ?? []}
          statusColumn="status"
        />
      </div>
    </div>
  );
}
