"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useConfirm } from "@/components/shared/use-confirm";

interface Erotica {
  id: number;
  title: string | null;
  content: string | null;
  credits: number;
}

export default function EditEroticaForm({ erotica }: { erotica: Erotica }) {
  const router = useRouter();
  const [saving, setSaving] = useState(false);
  const [title, setTitle] = useState(erotica.title || "");
  const [content, setContent] = useState(erotica.content || "");
  const [credits, setCredits] = useState(erotica.credits);
  const { confirm: askConfirm, dialog: confirmDialog } = useConfirm();

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const res = await fetch(`/api/erotica/${erotica.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title, content, credits }),
      });
      if (!res.ok) throw new Error("Failed");
      router.push(`/erotica/${erotica.id}`);
    } catch {
      alert("Failed to update erotica.");
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete() {
    if (!(await askConfirm({ title: "Delete story", message: "Delete this story? This cannot be undone." }))) return;
    try {
      await fetch(`/api/erotica/${erotica.id}`, { method: "DELETE" });
      router.push("/dashboard");
    } catch {
      alert("Failed to delete erotica.");
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {confirmDialog}
      <div className="bg-surface rounded-lg p-6 space-y-4">
        <div>
          <label className="block text-sm font-medium text-text mb-1">Title</label>
          <input type="text" required value={title} onChange={(e) => setTitle(e.target.value)} className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary" />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-1">Story</label>
          <textarea rows={16} required value={content} onChange={(e) => setContent(e.target.value)} className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary" />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-1">Credits (0 = free)</label>
          <input type="number" min={0} value={credits} onChange={(e) => setCredits(Number(e.target.value))} className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary" />
        </div>
      </div>

      <div className="flex items-center justify-between">
        <button type="button" onClick={handleDelete} className="text-red-400 hover:text-red-300 text-sm">
          Delete Story
        </button>
        <button type="submit" disabled={saving} className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50">
          {saving ? "Saving..." : "Save Changes"}
        </button>
      </div>
    </form>
  );
}
