import { db } from "@/lib/db"
import { notFound } from "next/navigation"
import { DropForm } from "@/components/admin/drop-form"
import { Button } from "@/components/ui/button"
import { updateDrop, deleteDrop, regenerateDropConcept } from "../actions"

export const metadata = { title: "Admin — Modifier le drop" }

export default async function EditDropPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const [drop, collaborators] = await Promise.all([
    db.drop.findUnique({ where: { id } }),
    db.collaborator.findMany({ orderBy: { name: "asc" } }),
  ])

  if (!drop) notFound()

  const updateWithId = updateDrop.bind(null, id)
  const deleteWithId = deleteDrop.bind(null, id)
  const regenerateWithId = regenerateDropConcept.bind(null, id)

  return (
    <div>
      <div className="flex items-center justify-between mb-8">
        <h1 className="text-2xl font-heading font-bold uppercase tracking-tight text-[var(--text)]">
          Modifier « {drop.name} »
        </h1>
        <form action={deleteWithId}>
          <Button type="submit" variant="destructive" size="sm">
            Supprimer
          </Button>
        </form>
      </div>

      <div className="border border-[var(--border)] bg-[var(--surface)] p-6 max-w-2xl mb-8">
        <div className="flex items-center justify-between mb-4">
          <p className="font-mono text-xs uppercase tracking-widest text-[var(--accent)]">
            Concept PROTO
            {drop.aiConceptSource && (
              <span className="text-[var(--text-muted)] normal-case tracking-normal ml-2">
                ({drop.aiConceptSource === "llm" ? "généré par IA" : "généré par règles"})
              </span>
            )}
          </p>
          <form action={regenerateWithId}>
            <Button type="submit" variant="outline" size="sm">
              Régénérer
            </Button>
          </form>
        </div>
        {drop.aiConcept ? (
          <p className="text-sm text-[var(--text-secondary)] leading-relaxed whitespace-pre-line">
            {drop.aiConcept}
          </p>
        ) : (
          <p className="text-sm text-[var(--text-muted)]">
            Pas encore de concept généré — clique sur « Régénérer ».
          </p>
        )}
      </div>

      <DropForm
        action={updateWithId}
        collaborators={collaborators}
        submitLabel="Enregistrer"
        defaultValues={{
          name: drop.name,
          description: drop.description,
          releaseDate: drop.releaseDate.toISOString().slice(0, 10),
          status: drop.status,
          coverImage: drop.coverImage,
          workshopVideoUrl: drop.workshopVideoUrl,
          stylistId: drop.stylistId,
          artistId: drop.artistId,
          aiAgentId: drop.aiAgentId,
          electricianId: drop.electricianId,
          isDraft: drop.isDraft,
        }}
      />
    </div>
  )
}
