"use client";

/**
 * VideoEmbedField — client komponenta za admin forme.
 *
 * Daje dve opcije:
 *   1) PASTE URL — YouTube, Vimeo ili direktan MP4 link
 *   2) UPLOAD FAJL — direct-to-R2 upload za vlastite MP4/WebM video-e
 *
 * Live preview se renderuje čim URL postaje validan (iframe za YT/Vimeo,
 * native <video> za MP4). Posle upload-a, URL se automatski popuni i
 * postavi se u hidden input koji ide u parent form.
 */

import { useState } from "react";

import { VideoUploader } from "@/components/admin/media/VideoUploader";
import { detectVideoSource } from "@/lib/video/embed";

const inputCls =
  "h-10 w-full rounded-xl border border-border bg-white px-4 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/15 transition";

interface VideoEmbedFieldProps {
  /** name na URL polju — server prima ovo. */
  urlName: string;
  /** name na title polju (opciono). */
  titleName?: string;
  /** Inicijalna vrednost video URL-a iz baze. */
  defaultUrl?: string | null;
  /** Inicijalna vrednost video naslova iz baze. */
  defaultTitle?: string | null;
  /** Helper tekst ispod URL polja. */
  hint?: string;
}

export function VideoEmbedField({
  urlName,
  titleName,
  defaultUrl,
  defaultTitle,
  hint,
  uploadDirectory = "videos",
}: VideoEmbedFieldProps & { uploadDirectory?: string }) {
  const [url, setUrl] = useState(defaultUrl ?? "");
  const [title, setTitle] = useState(defaultTitle ?? "");
  const [mode, setMode] = useState<"link" | "upload">("link");
  const preview = detectVideoSource(url.trim());

  return (
    <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
      <div className="space-y-4">
        {/* Mode toggle — Link ili Upload */}
        <div className="inline-flex rounded-full bg-[#faf9f7] p-1">
          <button
            type="button"
            onClick={() => setMode("link")}
            className={`inline-flex h-8 items-center gap-1.5 rounded-full px-4 text-xs font-bold transition ${
              mode === "link"
                ? "bg-white text-foreground shadow-sm"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >
            🔗 Paste link
          </button>
          <button
            type="button"
            onClick={() => setMode("upload")}
            className={`inline-flex h-8 items-center gap-1.5 rounded-full px-4 text-xs font-bold transition ${
              mode === "upload"
                ? "bg-white text-foreground shadow-sm"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >
            📤 Upload fajl
          </button>
        </div>

        {mode === "link" ? (
          <div className="space-y-1.5">
            <label className="block text-sm font-semibold text-foreground">Video link</label>
            {hint ? <p className="text-xs leading-5 text-muted-foreground">{hint}</p> : <p className="text-xs leading-5 text-muted-foreground">Podržano: YouTube, Vimeo, ili direktan MP4 link.</p>}
            <input
              type="url"
              name={urlName}
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              className={inputCls}
              placeholder="https://www.youtube.com/watch?v=..."
            />
          </div>
        ) : (
          <div className="space-y-2">
            <label className="block text-sm font-semibold text-foreground">Uploaduj video</label>
            <p className="text-xs leading-5 text-muted-foreground">
              MP4 / WebM / MOV — direktno na naš storage. Posle uploada,
              URL se automatski postavi u polje desno.
            </p>
            <VideoUploader
              directory={uploadDirectory}
              hint="Snimak ide pravo na Cloudflare R2 — bez Vercel 4.5MB limita."
              onUploaded={(result) => {
                setUrl(result.url);
                setMode("link"); // prebaci se na link mode da se vidi preview
              }}
            />
            {/* Hidden input čuva URL i kad si u upload mode-u, da form save dobije vrednost */}
            <input type="hidden" name={urlName} value={url} />
          </div>
        )}
        {titleName ? (
          <div className="space-y-1.5">
            <label className="block text-sm font-semibold text-foreground">Naslov video-a</label>
            <input
              type="text"
              name={titleName}
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className={inputCls}
              placeholder="Opciono — npr. Trailer ili Aftermovie"
            />
          </div>
        ) : null}
      </div>
      <div className="space-y-2">
        <p className="text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground">Pregled</p>
        {url.trim().length === 0 ? (
          <div className="flex aspect-video items-center justify-center rounded-2xl border border-dashed border-border bg-muted/40 text-xs text-muted-foreground">
            Unesi link da bi se prikazao pregled
          </div>
        ) : preview.source && preview.embedUrl ? (
          <div className="aspect-video overflow-hidden rounded-2xl border border-border bg-zinc-900 shadow-sm">
            {preview.source === "mp4" ? (
              <video src={preview.embedUrl} controls preload="metadata" className="h-full w-full" />
            ) : (
              <iframe
                src={preview.embedUrl}
                title="Video pregled"
                loading="lazy"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
                className="h-full w-full"
              />
            )}
          </div>
        ) : (
          <div className="flex aspect-video items-center justify-center rounded-2xl border border-amber-200 bg-amber-50 px-4 text-center text-xs text-amber-800">
            Link nije prepoznat — proveri da li je YouTube/Vimeo/MP4 URL
          </div>
        )}
      </div>
    </div>
  );
}
