"use client";

import { useState } from "react";
import { getArtifactReadUrl } from "@/lib/blob-client";
import type { ArtifactSummary } from "@/lib/types";

export function ArtifactPanel({
  artifacts,
  onCreate,
  isCreating = false,
}: {
  artifacts: ArtifactSummary[];
  onCreate: (input: {
    title: string;
    artifactType: "file" | "summary" | "extraction" | "citation" | "export";
    description?: string;
    blobPath?: string;
  }) => Promise<void>;
  isCreating?: boolean;
}) {
  const [openingId, setOpeningId] = useState<string | null>(null);
  const [title, setTitle] = useState("");
  const [artifactType, setArtifactType] = useState<"file" | "summary" | "extraction" | "citation" | "export">("file");
  const [description, setDescription] = useState("");
  const [blobPath, setBlobPath] = useState("");

  async function handleOpenArtifact(artifact: ArtifactSummary) {
    if (!artifact.blobPath) {
      return;
    }

    try {
      setOpeningId(artifact.id);
      const url = await getArtifactReadUrl(artifact.blobPath);
      window.open(url, "_blank", "noopener,noreferrer");
    } finally {
      setOpeningId(null);
    }
  }

  async function handleCreateArtifact() {
    if (!title.trim()) {
      return;
    }

    await onCreate({
      title: title.trim(),
      artifactType,
      description: description.trim() || undefined,
      blobPath: blobPath.trim() || undefined,
    });

    setTitle("");
    setArtifactType("file");
    setDescription("");
    setBlobPath("");
  }

  return (
    <section className="surface-card" style={{ padding: "var(--nl-space-5)", display: "grid", gap: "var(--nl-space-3)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", gap: "var(--nl-space-3)", alignItems: "center" }}>
        <div style={{ fontWeight: 700 }}>Artifacts</div>
        <span className="badge">blob-backed view</span>
      </div>
      <div className="surface-muted" style={{ padding: "var(--nl-space-3)", display: "grid", gap: "var(--nl-space-3)" }}>
        <div style={{ display: "grid", gap: "var(--nl-space-2)" }}>
          <label htmlFor="artifact-title" style={{ color: "var(--nl-text-secondary)" }}>
            Add artifact
          </label>
          <input
            id="artifact-title"
            className="input-shell"
            value={title}
            onChange={(event) => setTitle(event.target.value)}
            placeholder="Artifact title"
          />
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "minmax(140px, 180px) minmax(0, 1fr)", gap: "var(--nl-space-3)" }}>
          <select
            className="input-shell"
            value={artifactType}
            onChange={(event) => setArtifactType(event.target.value as "file" | "summary" | "extraction" | "citation" | "export")}
          >
            <option value="file">file</option>
            <option value="summary">summary</option>
            <option value="extraction">extraction</option>
            <option value="citation">citation</option>
            <option value="export">export</option>
          </select>
          <input
            className="input-shell"
            value={blobPath}
            onChange={(event) => setBlobPath(event.target.value)}
            placeholder="Optional blob path"
          />
        </div>
        <textarea
          className="input-shell"
          value={description}
          onChange={(event) => setDescription(event.target.value)}
          placeholder="Description"
          style={{ minHeight: 96, resize: "vertical" }}
        />
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <button
            type="button"
            disabled={isCreating}
            onClick={() => {
              void handleCreateArtifact();
            }}
            style={{
              border: "none",
              borderRadius: "var(--nl-radius-md)",
              padding: "8px 12px",
              background: "var(--nl-accent-primary)",
              color: "var(--nl-text-primary)",
              fontWeight: 600,
            }}
          >
            {isCreating ? "Adding…" : "Add artifact"}
          </button>
        </div>
      </div>
      {artifacts.map((artifact) => (
        <div key={artifact.id} className="surface-muted" style={{ padding: "var(--nl-space-3)", display: "flex", justifyContent: "space-between", gap: "var(--nl-space-3)", alignItems: "center" }}>
          <div style={{ display: "grid", gap: 4 }}>
            <strong>{artifact.name}</strong>
            <span style={{ color: "var(--nl-text-secondary)" }}>{artifact.type}</span>
          </div>
          <div style={{ display: "flex", gap: "var(--nl-space-3)", alignItems: "center" }}>
            <span style={{ color: "var(--nl-text-secondary)" }}>{artifact.status}</span>
            {artifact.blobPath ? (
              <button
                type="button"
                className="badge"
                onClick={() => {
                  void handleOpenArtifact(artifact);
                }}
                disabled={openingId === artifact.id}
              >
                {openingId === artifact.id ? "Opening…" : "Open"}
              </button>
            ) : null}
          </div>
        </div>
      ))}
    </section>
  );
}
