"use client";

import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import type { SignatureArtist } from "@/types/event";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useConfirmDialog } from "@/components/ui/confirm-dialog";
import { useToast } from "@/components/ui/toast";
import { cardClasses } from "@/components/ui/styles";
import { cn } from "@/lib/utils";
import { clientFetch } from "@/lib/api/client";
import { MediaSlot } from "./media-slot";

interface FormState {
  name: string;
  role: string;
}

const EMPTY_FORM: FormState = { name: "", role: "" };

function ArtistFields({ form, setForm }: { form: FormState; setForm: (form: FormState) => void }) {
  return (
    <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
      <label className="flex flex-col gap-1 text-sm font-medium">
        Artist Name
        <Input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
      </label>
      <label className="flex flex-col gap-1 text-sm font-medium">
        Role (optional)
        <Input
          placeholder="e.g. Headliner"
          value={form.role}
          onChange={(e) => setForm({ ...form, role: e.target.value })}
        />
      </label>
    </div>
  );
}

function toPayload(form: FormState) {
  return { name: form.name, role: form.role || null };
}

export function SignatureArtistManager({ eventId, artists }: { eventId: number; artists: SignatureArtist[] }) {
  const router = useRouter();
  const [showCreate, setShowCreate] = useState(false);
  const [createForm, setCreateForm] = useState<FormState>(EMPTY_FORM);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editForm, setEditForm] = useState<FormState>(EMPTY_FORM);
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const { confirm, dialog } = useConfirmDialog();
  const { toast } = useToast();

  async function handleCreate(formEvent: FormEvent<HTMLFormElement>) {
    formEvent.preventDefault();
    setError(null);
    setIsSubmitting(true);

    const res = await clientFetch(`/api/admin/events/${eventId}/signature-artists`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(toPayload(createForm)),
    });

    setIsSubmitting(false);
    const body = await res.json().catch(() => null);

    if (!res.ok) {
      const message = body?.errors?.name?.[0] ?? body?.message ?? "Failed to add artist.";
      setError(message);
      toast(message, "error");
      return;
    }

    setShowCreate(false);
    setCreateForm(EMPTY_FORM);
    toast("Artist added successfully.", "success");
    router.refresh();
  }

  function startEdit(artist: SignatureArtist) {
    setEditingId(artist.id);
    setEditForm({ name: artist.name, role: artist.role ?? "" });
  }

  async function handleUpdate(formEvent: FormEvent<HTMLFormElement>, artistId: number) {
    formEvent.preventDefault();
    setError(null);
    setIsSubmitting(true);

    const res = await clientFetch(`/api/admin/events/${eventId}/signature-artists/${artistId}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(toPayload(editForm)),
    });

    setIsSubmitting(false);
    const body = await res.json().catch(() => null);

    if (!res.ok) {
      const message = body?.errors?.name?.[0] ?? body?.message ?? "Failed to update artist.";
      setError(message);
      toast(message, "error");
      return;
    }

    setEditingId(null);
    toast("Artist updated successfully.", "success");
    router.refresh();
  }

  async function handleDelete(artistId: number) {
    if (!(await confirm("Delete this artist?"))) return;

    setError(null);
    setDeletingId(artistId);
    const res = await clientFetch(`/api/admin/events/${eventId}/signature-artists/${artistId}`, {
      method: "DELETE",
    });
    setDeletingId(null);
    const body = await res.json().catch(() => null);

    if (!res.ok) {
      const message = body?.message ?? "Failed to delete artist.";
      setError(message);
      toast(message, "error");
      return;
    }
    toast("Artist deleted successfully.", "success");
    router.refresh();
  }

  return (
    <div>
      {dialog}
      {error && <p className="mb-3 text-sm text-red-600">{error}</p>}

      <div className={cn("flex flex-col divide-y divide-kolabora-neutral-dark/10", cardClasses())}>
        {artists.length === 0 && (
          <p className="px-4 py-6 text-center text-sm text-kolabora-neutral-dark/70">No artists yet.</p>
        )}
        {artists.map((artist) => (
          <div key={artist.id} className="p-4">
            {editingId === artist.id ? (
              <form onSubmit={(e) => handleUpdate(e, artist.id)}>
                <ArtistFields form={editForm} setForm={setEditForm} />
                <div className="mt-3 flex gap-2">
                  <Button type="submit" loading={isSubmitting}>
                    Save
                  </Button>
                  <Button type="button" variant="secondary" onClick={() => setEditingId(null)} disabled={isSubmitting}>
                    Cancel
                  </Button>
                </div>
              </form>
            ) : (
              <div className="flex items-center justify-between gap-4">
                <div className="min-w-0">
                  <p className="truncate font-medium">{artist.name}</p>
                  {artist.role && <p className="truncate text-sm text-kolabora-neutral-dark/70">{artist.role}</p>}
                </div>
                <div className="flex shrink-0 gap-2">
                  <Button type="button" variant="secondary" size="sm" onClick={() => startEdit(artist)}>
                    Edit
                  </Button>
                  <Button
                    type="button"
                    variant="danger"
                    size="sm"
                    onClick={() => handleDelete(artist.id)}
                    loading={deletingId === artist.id}
                  >
                    Delete
                  </Button>
                </div>
              </div>
            )}
            <div className="mt-3 border-t border-kolabora-neutral-dark/10 pt-3">
              <MediaSlot
                label="Photo"
                fieldName="photo"
                endpoint={`/api/admin/events/${eventId}/signature-artists/${artist.id}/photo`}
                current={artist.photo_url}
                hint="JPG/PNG/WEBP, max 5MB."
              />
            </div>
          </div>
        ))}
      </div>

      {showCreate ? (
        <form onSubmit={handleCreate} className={cn("mt-4", cardClasses("p-4"))}>
          <ArtistFields form={createForm} setForm={setCreateForm} />
          <div className="mt-3 flex gap-2">
            <Button type="submit" loading={isSubmitting}>
              Save Artist
            </Button>
            <Button type="button" variant="secondary" onClick={() => setShowCreate(false)} disabled={isSubmitting}>
              Cancel
            </Button>
          </div>
        </form>
      ) : (
        <Button type="button" onClick={() => setShowCreate(true)} className="mt-4">
          + Add Artist
        </Button>
      )}
    </div>
  );
}
