"use client";

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

export default function NewShortForm({ clientId }: { clientId: string }) {
  const router = useRouter();
  const [sourceUrl, setSourceUrl] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError(null);

    const res = await fetch("/api/projects", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ clientId, sourceUrl }),
    });

    const data = await res.json().catch(() => ({}));
    setLoading(false);

    if (!res.ok) {
      setError(data.error ?? "Failed to start project");
      return;
    }

    setSourceUrl("");
    router.push(`/dashboard/projects/${data.id}`);
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-3 rounded-lg border border-gray-200 bg-white p-4">
      <label className="text-xs font-medium text-gray-600">Reference YouTube video URL</label>
      <div className="flex gap-2">
        <input
          type="url"
          required
          placeholder="https://www.youtube.com/watch?v=..."
          value={sourceUrl}
          onChange={(e) => setSourceUrl(e.target.value)}
          className="flex-1 rounded-md border border-gray-300 px-3 py-2 text-sm"
        />
        <button
          type="submit"
          disabled={loading}
          className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
        >
          {loading ? "Starting..." : "Recreate as Short"}
        </button>
      </div>
      <p className="text-xs text-gray-500">
        We extract the theme/format, then generate a brand-new script, voice, visuals, and
        music — nothing from the source video is reused.
      </p>
      {error && <p className="text-sm text-red-600">{error}</p>}
    </form>
  );
}
