import Link from "next/link";
import { getFile } from "@/lib/store";
import { notFound } from "next/navigation";
import { getSession } from "@/lib/session";
import CopyLinkButton from "./CopyLinkButton";
import DeleteFileButton from "./DeleteFileButton";

function formatBytes(n: number) {
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
  return `${(n / 1024 / 1024).toFixed(2)} MB`;
}

function MetaRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex items-start justify-between gap-6 py-3 border-b border-white/5 last:border-0">
      <span className="text-sm text-slate-500 shrink-0">{label}</span>
      <span className="text-sm text-slate-200 text-right font-mono">{value}</span>
    </div>
  );
}

export default async function FileDetailPage({
  params,
}: {
  params: Promise<{ token: string }>;
}) {
  const { token } = await params;
  const [record, session] = await Promise.all([getFile(token), getSession()]);
  if (!record) notFound();
  const isAdmin = session?.role === "admin";

  const isBackerup = record.type === "backerup";
  const downloadUrl = `/api/files/${token}/download`;
  const title = record.displayName ?? record.containerName ?? record.originalName;

  return (
    <div className="mx-auto max-w-2xl px-6 py-16">
      {/* Back */}
      <Link
        href="/browse"
        className="inline-flex items-center gap-1.5 text-xs text-slate-500 hover:text-slate-300 transition-colors mb-8"
      >
        <svg viewBox="0 0 24 24" className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="2.5" aria-hidden="true">
          <path d="M19 12H5M12 5l-7 7 7 7" />
        </svg>
        Back to browse
      </Link>

      {/* Header card */}
      <div className="rounded-2xl border border-white/6 glass p-7 mb-6">
        {/* Badges */}
        <div className="flex flex-wrap items-center gap-2 mb-4">
          {isBackerup ? (
            <span className="rounded-full bg-cyan-500/12 border border-cyan-500/25 px-3 py-1 text-xs font-semibold text-cyan-400">
              .backerup archive
            </span>
          ) : (
            <span className="rounded-full bg-violet-500/12 border border-violet-500/25 px-3 py-1 text-xs font-semibold text-violet-400">
              .json config
            </span>
          )}
          {record.group && (
            <span className="rounded-full bg-white/5 border border-white/10 px-3 py-1 text-xs font-medium text-slate-400">
              {record.group}
            </span>
          )}
          <span className="font-mono text-xs text-slate-600 ml-auto">{record.originalName}</span>
        </div>

        {/* Title */}
        <h1 className="text-3xl font-extrabold tracking-tight text-white leading-snug">
          {title}
        </h1>

        {/* Image */}
        {record.image && (
          <p className="mt-2 font-mono text-sm text-slate-400">{record.image}</p>
        )}

        {/* Description */}
        {record.description && (
          <p className="mt-4 text-slate-400 leading-relaxed border-t border-white/5 pt-4">
            {record.description}
          </p>
        )}
      </div>

      {/* Metadata */}
      <div className="rounded-2xl border border-white/6 glass px-6 py-2 mb-6">
        <MetaRow label="File size" value={formatBytes(record.size)} />
        <MetaRow
          label="Uploaded"
          value={new Date(record.uploadedAt).toLocaleString("en-US", {
            month: "long",
            day: "numeric",
            year: "numeric",
            hour: "2-digit",
            minute: "2-digit",
          })}
        />
        {record.group && <MetaRow label="Group" value={record.group} />}
        {record.containerName && <MetaRow label="Container name" value={record.containerName} />}
        {record.image && <MetaRow label="Image" value={record.image} />}
        <MetaRow label="Share token" value={token} />
      </div>

      {/* Docker restore snippet for configs */}
      {!isBackerup && record.image && (
        <div className="rounded-2xl border border-white/6 glass overflow-hidden mb-6">
          <div className="flex items-center gap-2 border-b border-white/6 px-5 py-3 bg-white/2">
            <span className="h-2.5 w-2.5 rounded-full bg-red-500/70" />
            <span className="h-2.5 w-2.5 rounded-full bg-yellow-500/70" />
            <span className="h-2.5 w-2.5 rounded-full bg-emerald-500/70" />
            <span className="ml-2 text-xs font-mono text-slate-500">quick restore</span>
          </div>
          <pre className="overflow-x-auto p-5 text-xs font-mono leading-6 text-slate-300">
            <span className="text-slate-600 select-none"># Pull the image used by this config</span>{"\n"}
            <span className="text-cyan-500 select-none">$ </span>
            <span>docker pull {record.image}</span>{"\n\n"}
            <span className="text-slate-600 select-none"># Download & import this config into Backerup to restore</span>{"\n"}
            <span className="text-cyan-500 select-none">$ </span>
            <span>curl -O {`{{BACKERUP_URL}}`}/api/files/{token}/download</span>
          </pre>
        </div>
      )}

      {/* Actions */}
      <div className="space-y-3">
        <a
          href={downloadUrl}
          className="flex w-full items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-bold text-slate-900 transition-all hover:brightness-110 hover:scale-[1.01] active:scale-[0.99]"
          style={{ background: "linear-gradient(135deg, #22d3ee, #06b6d4)" }}
          download={record.originalName}
        >
          <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2.5" aria-hidden="true">
            <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
          </svg>
          Download {record.originalName}
        </a>

        <CopyLinkButton token={token} />

        {isAdmin && (
          <DeleteFileButton token={token} name={title} />
        )}

        <Link
          href="/browse"
          className="flex w-full items-center justify-center gap-2 rounded-xl border border-white/8 bg-white/3 py-3 text-sm font-medium text-slate-400 hover:text-white hover:bg-white/6 transition-all"
        >
          Browse more configs
        </Link>
      </div>

      {/* Warning for .backerup */}
      {isBackerup && (
        <div className="mt-6 flex gap-3 rounded-xl border border-amber-500/20 bg-amber-500/5 p-4">
          <span className="text-amber-400 shrink-0 mt-0.5">
            <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
            </svg>
          </span>
          <p className="text-xs text-amber-300 leading-relaxed">
            <strong className="font-semibold">Note:</strong> This is a full .backerup archive. It may contain volume data
            in addition to the container config. Import it into Backerup to restore or clone the container.
          </p>
        </div>
      )}
    </div>
  );
}


