"use client";

import { useRef, useState } from "react";
import { StateNotice } from "@/components/StateNotice";
import { Badge, Button, Card, Input, Select, Textarea } from "@/components/ui/Primitives";
import { getArtifactReadUrl, uploadArtifact } from "@/lib/blob-client";
import { toast } from "@/lib/toast";
import { getEmptyState, toUserFacingState, type UserFacingState } from "@/lib/user-facing-states";
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 [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [title, setTitle] = useState("");
  const [artifactType, setArtifactType] = useState<"file" | "summary" | "extraction" | "citation" | "export">("file");
  const [description, setDescription] = useState("");
  const [blobPath, setBlobPath] = useState("");
  const [noticeState, setNoticeState] = useState<UserFacingState | null>(null);

  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 handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    setNoticeState(null);
    try {
      const path = `artifacts/${crypto.randomUUID()}/${file.name}`;
      const result = await uploadArtifact(file, path);
      await onCreate({
        title: file.name,
        artifactType: "file",
        description: `Uploaded file (${(result.sizeBytes / 1024).toFixed(1)} KB)`,
        blobPath: result.blobPath,
      });
      toast.success("File uploaded");
    } catch (err) {
      const state = toUserFacingState(err, "blob");
      setNoticeState(state);
      toast.error(state.message);
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  }

  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("");
    setNoticeState(null);
  }

  return (
    <Card padding="md" className="grid gap-3">
      <div className="flex items-center justify-between gap-3">
        <div className="font-bold">Artifacts</div>
        <Badge variant="info">blob-backed view</Badge>
      </div>
      <div className="grid gap-3 rounded-[var(--nl-radius-sm)] bg-[color:var(--nl-surface-muted)] p-3">
        <Input
          id="artifact-title"
          label="Add artifact"
          value={title}
          onChange={(event) => setTitle(event.target.value)}
          placeholder="Artifact title"
          aria-label="Artifact title"
        />
        <div className="grid gap-3 [grid-template-columns:minmax(140px,180px)_minmax(0,1fr)]">
          <Select
            value={artifactType}
            onChange={(event) => setArtifactType(event.target.value as "file" | "summary" | "extraction" | "citation" | "export")}
            aria-label="Artifact type"
            options={[
              { value: "file", label: "file" },
              { value: "summary", label: "summary" },
              { value: "extraction", label: "extraction" },
              { value: "citation", label: "citation" },
              { value: "export", label: "export" },
            ]}
          />
          <Input
            value={blobPath}
            onChange={(event) => setBlobPath(event.target.value)}
            placeholder="Optional blob path"
            aria-label="Artifact blob path"
          />
        </div>
        <Textarea
          value={description}
          onChange={(event) => setDescription(event.target.value)}
          placeholder="Description"
          aria-label="Artifact description"
          className="min-h-[96px] resize-y"
        />
        <div style={{ display: "flex", justifyContent: "flex-end", gap: "var(--nl-space-2)" }}>
          <input ref={fileInputRef} type="file" hidden onChange={handleFileUpload} />
          <Button
            type="button"
            variant="secondary"
            disabled={uploading}
            onClick={() => fileInputRef.current?.click()}
          >
            {uploading ? "Uploading…" : "Upload file"}
          </Button>
          <Button
            type="button"
            disabled={isCreating}
            onClick={() => {
              void handleCreateArtifact();
            }}
          >
            {isCreating ? "Adding…" : "Add artifact"}
          </Button>
        </div>
      </div>
      {noticeState ? (
        <StateNotice
          state={noticeState}
          compact
          onAction={noticeState.actionLabel ? () => fileInputRef.current?.click() : undefined}
        />
      ) : null}
      {artifacts.length === 0 ? (
        <StateNotice state={getEmptyState("blob", "artifacts")} compact />
      ) : null}
      {artifacts.map((artifact) => (
        <div key={artifact.id} className="flex items-center justify-between gap-3 rounded-[var(--nl-radius-sm)] bg-[color:var(--nl-surface-muted)] p-3">
          <div className="grid gap-1">
            <strong>{artifact.name}</strong>
            <span className="text-[color:var(--nl-text-secondary)]">{artifact.type}</span>
          </div>
          <div className="flex items-center gap-3">
            <span className="text-[color:var(--nl-text-secondary)]">{artifact.status}</span>
            {artifact.blobPath ? (
              <Button
                type="button"
                size="sm"
                variant="secondary"
                onClick={() => {
                  void handleOpenArtifact(artifact);
                }}
                disabled={openingId === artifact.id}
                aria-label={`Open artifact: ${artifact.name}`}
              >
                {openingId === artifact.id ? "Opening…" : "Open"}
              </Button>
            ) : null}
          </div>
        </div>
      ))}
    </Card>
  );
}
