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

function UploadIcon() {
  return (
    <svg viewBox="0 0 24 24" className="w-10 h-10" fill="none" stroke="currentColor" strokeWidth="1.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.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg viewBox="0 0 24 24" className="w-10 h-10" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
    </svg>
  );
}

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 [progress, setProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);

  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);
    setProgress(0);
    setError(null);

    // Animate a fake progress bar for perceived speed
    const interval = setInterval(() => {
      setProgress((p) => (p < 85 ? p + Math.random() * 8 : p));
    }, 200);

    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");

      clearInterval(interval);
      setProgress(100);
      await new Promise((r) => setTimeout(r, 400));
      router.push(`/files/${data.token}`);
    } catch (err) {
      clearInterval(interval);
      setError(err instanceof Error ? err.message : "Unknown error");
      setUploading(false);
      setProgress(0);
    }
  }

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

  return (
    <div className="mx-auto max-w-2xl px-6 py-16">
      {/* Header */}
      <div className="mb-10">
        <p className="text-xs font-semibold uppercase tracking-widest text-cyan-400 mb-2">
          Share
        </p>
        <h1 className="text-4xl font-extrabold tracking-tight text-white">
          Share a file
        </h1>
        <p className="mt-3 text-slate-400 leading-relaxed">
          Upload a{" "}
          <code className="font-mono text-slate-300 bg-white/5 px-1.5 py-0.5 rounded text-xs">.backerup</code>{" "}
          snapshot or{" "}
          <code className="font-mono text-slate-300 bg-white/5 px-1.5 py-0.5 rounded text-xs">.json</code>{" "}
          container config. Anyone with the link can browse and 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-14 text-center transition-all ${
            dragging
              ? "border-cyan-400 bg-cyan-500/8 scale-[1.01]"
              : file
              ? "border-emerald-500/50 bg-emerald-500/5"
              : "border-white/10 bg-white/2 hover:border-white/20 hover:bg-white/4"
          }`}
          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-emerald-400 mb-3">
                <CheckIcon />
              </div>
              <p className="font-semibold text-white">{file.name}</p>
              <p className="mt-1 text-sm text-slate-400">
                {formatBytes(file.size)} ·{" "}
                <button
                  type="button"
                  className="text-cyan-400 hover:text-cyan-300 transition-colors underline"
                  onClick={(e) => { e.stopPropagation(); setFile(null); setError(null); }}
                >
                  remove
                </button>
              </p>
              <div className="mt-3 flex flex-wrap items-center justify-center gap-2">
                <span
                  className={`rounded-full px-3 py-1 text-xs font-semibold border ${
                    isBackerup
                      ? "bg-cyan-500/12 border-cyan-500/30 text-cyan-400"
                      : "bg-violet-500/12 border-violet-500/30 text-violet-400"
                  }`}
                >
                  {isBackerup ? ".backerup archive" : ".json config"}
                </span>
              </div>
            </>
          ) : (
            <>
              <div className={`mb-4 transition-colors ${dragging ? "text-cyan-400" : "text-slate-600"}`}>
                <UploadIcon />
              </div>
              <p className="font-semibold text-slate-300">
                {dragging ? "Drop it!" : "Drop a file or click to browse"}
              </p>
              <p className="mt-1.5 text-xs text-slate-600">
                Accepts{" "}
                <code className="font-mono text-slate-500">.backerup</code> and{" "}
                <code className="font-mono text-slate-500">.json</code> — up to 500 MB
              </p>
            </>
          )}
        </div>

        {/* ── Display name ── */}
        <div className="space-y-1.5">
          <label className="block text-sm font-medium text-slate-300" htmlFor="displayName">
            Display name{" "}
            <span className="text-slate-600 font-normal">(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-white/8 bg-white/4 px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-500/50 focus:bg-white/6 transition-all"
          />
          <p className="text-xs text-slate-600">Shown on the browse page instead of the raw filename.</p>
        </div>

        {/* ── Group ── */}
        <div className="space-y-1.5">
          <label className="block text-sm font-medium text-slate-300" htmlFor="group">
            Group{" "}
            <span className="text-slate-600 font-normal">(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-white/8 bg-white/4 px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-500/50 focus:bg-white/6 transition-all"
          />
          {existingGroups.length > 0 && (
            <datalist id="group-list">
              {existingGroups.map((g) => <option key={g} value={g} />)}
            </datalist>
          )}
          {existingGroups.length > 0 && (
            <div className="flex flex-wrap gap-1.5 pt-1">
              {existingGroups.map((g) => (
                <button
                  key={g}
                  type="button"
                  onClick={() => setGroup(g === group ? "" : g)}
                  className={`rounded-full px-2.5 py-0.5 text-xs transition-all ${
                    group === g
                      ? "bg-violet-500/20 border border-violet-500/40 text-violet-300"
                      : "bg-white/4 border border-white/8 text-slate-500 hover:text-slate-300"
                  }`}
                >
                  {g}
                </button>
              ))}
            </div>
          )}
          <p className="text-xs text-slate-600">
            Tag this upload so others can filter by group on the browse page.
          </p>
        </div>

        {/* ── Description ── */}
        <div className="space-y-1.5">
          <label className="block text-sm font-medium text-slate-300" htmlFor="desc">
            Description{" "}
            <span className="text-slate-600 font-normal">(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, includes all data volumes"
            className="w-full rounded-xl border border-white/8 bg-white/4 px-4 py-3 text-sm text-slate-200 placeholder-slate-600 outline-none focus:border-cyan-500/50 focus:bg-white/6 transition-all resize-none"
          />
        </div>

        {/* ── Warning for .backerup ── */}
        {isBackerup && (
          <div className="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">Heads up:</strong> .backerup files may contain volume
              data. Ensure you are not sharing sensitive database contents, secrets, or private keys.
            </p>
          </div>
        )}

        {/* ── Error ── */}
        {error && (
          <div className="flex items-start gap-3 rounded-xl border border-red-500/20 bg-red-500/8 px-4 py-3">
            <span className="text-red-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">
                <circle cx="12" cy="12" r="10" /><path d="m15 9-6 6m0-6 6 6" />
              </svg>
            </span>
            <p className="text-sm text-red-400">{error}</p>
          </div>
        )}

        {/* ── Progress bar ── */}
        {uploading && (
          <div className="space-y-1.5">
            <div className="flex items-center justify-between text-xs text-slate-500">
              <span>Uploading…</span>
              <span>{Math.round(progress)}%</span>
            </div>
            <div className="h-1.5 w-full rounded-full bg-white/5 overflow-hidden">
              <div
                className="h-full rounded-full transition-all duration-300"
                style={{
                  width: `${progress}%`,
                  background: "linear-gradient(90deg, #22d3ee, #818cf8)",
                }}
              />
            </div>
          </div>
        )}

        {/* ── Submit ── */}
        <button
          type="submit"
          disabled={!file || uploading}
          className="w-full 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] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:scale-100"
          style={{ background: "linear-gradient(135deg, #22d3ee, #06b6d4)" }}
        >
          {uploading ? "Uploading…" : "Upload & get share link"}
        </button>
      </form>
    </div>
  );
}
