"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";

const ACCEPTED = [".backerup", ".json"];
const MAX_BYTES = 500 * 1024 * 1024;

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`;
}

export default function SharePage() {
  const router = useRouter();
  const inputRef = useRef<HTMLInputElement>(null);
  const [file, setFile] = useState<File | null>(null);
  const [displayName, setDisplayName] = useState("");
  const [description, setDescription] = useState("");
  const [group, setGroup] = useState("");
  const [existingGroups, setExistingGroups] = useState<string[]>([]);
  const [dragging, setDragging] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Pre-fetch existing group names for autocomplete
  useEffect(() => {
    fetch("/api/files")
      .then((r) => r.json())
      .then((records: Array<{ group?: string }>) => {
        const groups = Array.from(
          new Set(records.map((r) => r.group).filter(Boolean) as string[])
        ).sort();
        setExistingGroups(groups);
      })
      .catch(() => { });
  }, []);

  function pickFile(f: File) {
    const name = f.name.toLowerCase();
    if (!ACCEPTED.some((ext) => name.endsWith(ext))) {
      setError("Only .backerup and .json files are accepted.");
      return;
    }
    if (f.size > MAX_BYTES) {
      setError("File exceeds the 500 MB limit.");
      return;
    }
    setError(null);
    setFile(f);
  }

  function onDrop(e: React.DragEvent) {
    e.preventDefault();
    setDragging(false);
    const dropped = e.dataTransfer.files[0];
    if (dropped) pickFile(dropped);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!file) return;
    setUploading(true);
    setError(null);
    try {
      const formData = new FormData();
      formData.append("file", file);
      if (displayName.trim()) formData.append("displayName", displayName.trim());
      formData.append("description", description);
      if (group.trim()) formData.append("group", group.trim());
      const res = await fetch("/api/upload", { method: "POST", body: formData });
      const data = (await res.json()) as { token?: string; error?: string };
      if (!res.ok || !data.token) {
        throw new Error(data.error ?? "Upload failed");
      }
      router.push(`/files/${data.token}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unknown error");
      setUploading(false);
    }
  }

  const isBackerup = file?.name.toLowerCase().endsWith(".backerup");

  return (
    <div className="mx-auto max-w-2xl px-6 py-16">
      <div className="mb-10">
        <h1 className="text-3xl font-bold text-white">Share a file</h1>
        <p className="mt-2 text-slate-400">
          Upload a{" "}
          <span className="font-mono text-slate-300">.backerup</span> snapshot or{" "}
          <span className="font-mono text-slate-300">.json</span> container config.
          Anyone with the link can download it.
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Drop zone */}
        <div
          className={`relative flex cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed px-8 py-16 text-center transition ${dragging
              ? "border-cyan-400 bg-cyan-500/10"
              : file
                ? "border-emerald-500/50 bg-emerald-500/5"
                : "border-slate-700 bg-slate-900/50 hover:border-slate-600"
            }`}
          onClick={() => inputRef.current?.click()}
          onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
          onDragLeave={() => setDragging(false)}
          onDrop={onDrop}
        >
          <input
            ref={inputRef}
            type="file"
            accept=".backerup,.json"
            className="hidden"
            onChange={(e) => { const f = e.target.files?.[0]; if (f) pickFile(f); }}
          />
          {file ? (
            <>
              <div className="text-4xl">{isBackerup ? "📦" : "🗂️"}</div>
              <p className="mt-3 font-semibold text-white">{file.name}</p>
              <p className="mt-1 text-xs text-slate-400">
                {formatBytes(file.size)} ·{" "}
                <button
                  type="button"
                  className="text-cyan-400 hover:underline"
                  onClick={(e) => { e.stopPropagation(); setFile(null); }}
                >
                  remove
                </button>
              </p>
            </>
          ) : (
            <>
              <div className="text-4xl text-slate-600">📁</div>
              <p className="mt-4 text-sm font-medium text-slate-300">
                Drop a file here or click to browse
              </p>
              <p className="mt-1 text-xs text-slate-500">
                Accepts <span className="font-mono">.backerup</span> and{" "}
                <span className="font-mono">.json</span> &mdash; up to 500 MB
              </p>
            </>
          )}
        </div>

        {/* Display name */}
        <div>
          <label className="mb-1.5 block text-sm font-medium text-slate-300" htmlFor="displayName">
            Display name <span className="text-slate-600">(optional)</span>
          </label>
          <input
            id="displayName"
            type="text"
            value={displayName}
            onChange={(e) => setDisplayName(e.target.value)}
            placeholder="e.g. Production Postgres backup"
            maxLength={120}
            className="w-full rounded-xl border border-slate-700 bg-slate-900 px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-500 transition-colors"
          />
          <p className="mt-1 text-xs text-slate-600">Shown instead of the raw filename.</p>
        </div>

        {/* Group */}
        <div>
          <label className="mb-1.5 block text-sm font-medium text-slate-300" htmlFor="group">
            Group <span className="text-slate-600">(optional)</span>
          </label>
          <input
            id="group"
            type="text"
            list="group-list"
            value={group}
            onChange={(e) => setGroup(e.target.value)}
            placeholder="e.g. production, homelab, postgres"
            maxLength={60}
            className="w-full rounded-xl border border-slate-700 bg-slate-900 px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-500 transition-colors"
          />
          {existingGroups.length > 0 && (
            <datalist id="group-list">
              {existingGroups.map((g) => (
                <option key={g} value={g} />
              ))}
            </datalist>
          )}
          <p className="mt-1 text-xs text-slate-600">
            Tag this upload so others can filter by group on the browse page.
          </p>
        </div>

        {/* Description */}
        <div>
          <label className="mb-1.5 block text-sm font-medium text-slate-300" htmlFor="desc">
            Description <span className="text-slate-600">(optional)</span>
          </label>
          <textarea
            id="desc"
            rows={3}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="e.g. Production Postgres 16 with TimescaleDB extension"
            className="w-full rounded-xl border border-slate-700 bg-slate-900 px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-500 transition-colors"
          />
        </div>

        {/* Warning for .backerup */}
        {isBackerup && (
          <div className="rounded-xl border border-amber-500/20 bg-amber-500/5 p-4 text-xs text-amber-300">
            <strong>Heads up:</strong> .backerup files may contain volume data. Make sure
            you are not sharing sensitive database contents or secrets.
          </div>
        )}

        {error && (
          <p className="rounded-lg bg-red-500/10 px-4 py-3 text-sm text-red-400">{error}</p>
        )}

        <button
          type="submit"
          disabled={!file || uploading}
          className="w-full rounded-xl bg-cyan-500 py-3 text-sm font-bold text-slate-900 transition hover:bg-cyan-400 disabled:cursor-not-allowed disabled:opacity-40"
        >
          {uploading ? "Uploading…" : "Upload & get link"}
        </button>
      </form>
    </div>
  );
}
