"use client";

import { useState } from "react";
import { useRef } from "react";
import { useRouter } from "next/navigation";
import { Bot, ImageUp, Save, Send } from "lucide-react";
import { RichTextEditor } from "@/components/editor/rich-text-editor";

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

export function ArticleComposer({ categories }: { categories: Category[] }) {
  const router = useRouter();
  const formRef = useRef<HTMLFormElement>(null);
  const [content, setContent] = useState("");
  const [coverImage, setCoverImage] = useState("");
  const [loading, setLoading] = useState(false);

  async function upload(event: React.ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];
    if (!file) return;
    const body = new FormData();
    body.append("file", file);
    const response = await fetch("/api/upload", { method: "POST", body });
    const data = await response.json();
    setCoverImage(data.url);
  }

  async function aiDraft() {
    const topic = window.prompt("Article topic");
    if (!topic) return;
    setLoading(true);
    const response = await fetch("/api/ai/generate", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ topic })
    });
    const data = await response.json();
    setContent(data.content || content);
    setLoading(false);
  }

  async function submit(event: React.FormEvent<HTMLFormElement> | null, status: "DRAFT" | "PENDING") {
    event?.preventDefault();
    if (!formRef.current) return;
    const form = new FormData(formRef.current);
    const payload = Object.fromEntries(form.entries());
    const response = await fetch("/api/articles", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...payload, content, coverImage, status })
    });
    if (response.ok) router.push("/dashboard");
  }

  return (
    <form ref={formRef} className="glass mt-8 space-y-5 rounded-lg p-5" onSubmit={(event) => submit(event, "PENDING")}>
      <input name="title" required className="w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-cyanx" placeholder="Headline" />
      <textarea name="excerpt" required className="min-h-24 w-full rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-cyanx" placeholder="SEO excerpt / standfirst" />
      <div className="grid gap-4 md:grid-cols-2">
        <select name="categoryId" required className="rounded-lg border border-white/10 bg-ink px-4 py-3 text-white outline-none focus:border-cyanx">
          <option value="">Choose category</option>
          {categories.map((category) => <option key={category.id} value={category.id}>{category.name}</option>)}
        </select>
        <input name="tags" className="rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-cyanx" placeholder="Tags, comma separated" />
      </div>
      <div className="grid gap-4 md:grid-cols-2">
        <label className="flex cursor-pointer items-center justify-center gap-2 rounded-lg border border-dashed border-white/16 bg-white/[.03] px-4 py-4 text-sm text-white/65 hover:border-cyanx">
          <ImageUp size={18} /> Upload featured image
          <input type="file" accept="image/*" className="hidden" onChange={upload} />
        </label>
        <input value={coverImage} onChange={(event) => setCoverImage(event.target.value)} className="rounded-lg border border-white/10 bg-white/5 px-4 py-3 text-white outline-none focus:border-cyanx" placeholder="Image URL" />
      </div>
      <RichTextEditor value={content} onChange={setContent} />
      <div className="flex flex-wrap gap-3">
        <button type="button" onClick={aiDraft} className="inline-flex items-center gap-2 rounded-full border border-white/12 px-5 py-3 text-sm font-semibold text-white hover:border-cyanx hover:text-cyanx">
          <Bot size={17} /> {loading ? "Generating..." : "AI draft"}
        </button>
        <button type="submit" className="inline-flex items-center gap-2 rounded-full bg-cyanx px-5 py-3 text-sm font-black text-ink">
          <Send size={17} /> Submit for approval
        </button>
        <button type="button" onClick={() => submit(null, "DRAFT")} className="inline-flex items-center gap-2 rounded-full border border-white/12 px-5 py-3 text-sm font-semibold text-white hover:border-cyanx">
          <Save size={17} /> Save draft
        </button>
      </div>
    </form>
  );
}
