"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";

type Category = { id: string; name: string };

export default function VideoForm({
  categories,
  initial,
  videoId,
}: {
  categories: Category[];
  initial?: any;
  videoId?: string;
}) {
  const router = useRouter();
  const [form, setForm] = useState({
    title: initial?.title || "",
    description: initial?.description || "",
    youtubeId: initial?.youtubeId || "",
    thumbnailUrl: initial?.thumbnailUrl || "",
    categoryId: initial?.categoryId || (categories[0]?.id ?? ""),
    accessTier: initial?.accessTier || "free",
    price: initial?.price?.toString() || "0",
    featured: initial?.featured || false,
    status: initial?.status || "draft",
    previewSeconds: initial?.previewSeconds?.toString() || "",
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  function update(key: string, value: any) {
    setForm((f) => ({ ...f, [key]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setError("");

    const url = videoId ? `/api/admin/videos/${videoId}` : "/api/admin/videos";
    const method = videoId ? "PATCH" : "POST";

    const res = await fetch(url, {
      method,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    });

    if (!res.ok) {
      const data = await res.json();
      setError(data.error || "Something went wrong.");
      setSaving(false);
      return;
    }

    router.push("/admin/videos");
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4 max-w-xl">
      <div>
        <label className="block text-sm mb-1 text-neutral-400">Title</label>
        <input required value={form.title} onChange={(e) => update("title", e.target.value)}
          className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600" />
      </div>

      <div>
        <label className="block text-sm mb-1 text-neutral-400">Description</label>
        <textarea value={form.description} onChange={(e) => update("description", e.target.value)} rows={3}
          className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600" />
      </div>

      <div>
        <label className="block text-sm mb-1 text-neutral-400">
          YouTube Video ID <span className="text-neutral-600">(private/unlisted — the part after v= in the URL)</span>
        </label>
        <input required value={form.youtubeId} onChange={(e) => update("youtubeId", e.target.value)}
          placeholder="e.g. dQw4w9WgXcQ"
          className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600" />
        <p className="text-xs text-neutral-600 mt-1">
          Note: private YouTube videos only play for signed-in Google accounts with access granted by the owner. Use "Unlisted" if you want anyone with your site to view it.
        </p>
      </div>

      <div>
        <label className="block text-sm mb-1 text-neutral-400">Thumbnail URL (optional — defaults to YouTube thumbnail)</label>
        <input value={form.thumbnailUrl} onChange={(e) => update("thumbnailUrl", e.target.value)}
          className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600" />
      </div>

      <div>
        <label className="block text-sm mb-1 text-neutral-400">Category</label>
        <select value={form.categoryId} onChange={(e) => update("categoryId", e.target.value)}
          className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600">
          {categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm mb-1 text-neutral-400">Access Tier</label>
          <select value={form.accessTier} onChange={(e) => update("accessTier", e.target.value)}
            className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600">
            <option value="free">Free</option>
            <option value="starter">Starter</option>
            <option value="plus">Plus</option>
            <option value="premium">Premium</option>
            <option value="ppv">One-time purchase ($)</option>
          </select>
        </div>
        {form.accessTier === "ppv" && (
          <div>
            <label className="block text-sm mb-1 text-neutral-400">Price ($)</label>
            <input type="number" step="0.01" value={form.price} onChange={(e) => update("price", e.target.value)}
              className="w-full bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600" />
          </div>
        )}
      </div>

      <div>
        <label className="block text-sm mb-1 text-neutral-400">
          Free preview length for non-members (seconds, optional)
        </label>
        <input type="number" min="0" value={form.previewSeconds} onChange={(e) => update("previewSeconds", e.target.value)}
          placeholder="Leave blank to use site default / no preview"
          className="w-full max-w-xs bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600" />
        <p className="text-xs text-neutral-600 mt-1">
          Non-members/insufficient-tier visitors can watch this many seconds before being asked to upgrade.
        </p>
      </div>

      <div className="flex items-center gap-6">
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={form.featured} onChange={(e) => update("featured", e.target.checked)} />
          Featured on homepage
        </label>
        <label className="flex items-center gap-2 text-sm">
          Status:
          <select value={form.status} onChange={(e) => update("status", e.target.value)}
            className="bg-neutral-900 border border-neutral-800 rounded-md px-2 py-1 text-sm outline-none focus:border-red-600">
            <option value="draft">Draft</option>
            <option value="published">Published</option>
          </select>
        </label>
      </div>

      {error && <p className="text-red-500 text-sm">{error}</p>}

      <button type="submit" disabled={saving} className="btn-primary px-6 py-2.5">
        {saving ? "Saving..." : videoId ? "Save Changes" : "Create Video"}
      </button>
    </form>
  );
}
