"use client";

import Image from "next/image";
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ADMIN_API } from "@/lib/constants";
import { isUploadAssetPath } from "@/lib/image-url";
import type { Ingredient } from "@/generated/prisma/client";

export function AdminIngredients() {
  const router = useRouter();
  const [items, setItems] = useState<Ingredient[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState({
    name: "",
    price: "",
    imageUrl: "",
  });

  const load = useCallback(async () => {
    const res = await fetch(`${ADMIN_API}/ingredients`, {
      credentials: "include",
    });
    if (res.status === 401) {
      router.replace("/admin/login");
      return;
    }
    const data = await res.json();
    setItems(Array.isArray(data) ? data : []);
    setLoading(false);
  }, [router]);

  useEffect(() => {
    load();
  }, [load]);

  function resetForm() {
    setEditingId(null);
    setForm({ name: "", price: "", imageUrl: "" });
  }

  function startEdit(ing: Ingredient) {
    setEditingId(ing.id);
    setForm({
      name: ing.name,
      price: String(ing.price),
      imageUrl: ing.imageUrl ?? "",
    });
  }

  async function uploadFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      const res = await fetch(`${ADMIN_API}/upload`, {
        method: "POST",
        body: fd,
        credentials: "include",
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        alert(typeof data.error === "string" ? data.error : "Échec de l’envoi");
        return;
      }
      if (data.url) setForm((f) => ({ ...f, imageUrl: data.url }));
    } finally {
      setUploading(false);
      e.target.value = "";
    }
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    const price = parseFloat(form.price.replace(",", "."));
    if (Number.isNaN(price) || price < 0) return;
    setSaving(true);
    try {
      const body = {
        name: form.name.trim(),
        price,
        imageUrl: form.imageUrl.trim() || null,
      };
      if (editingId) {
        const res = await fetch(`${ADMIN_API}/ingredients/${editingId}`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify(body),
        });
        if (res.status === 401) {
          router.replace("/admin/login");
          return;
        }
        if (!res.ok) return;
      } else {
        const res = await fetch(`${ADMIN_API}/ingredients`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify(body),
        });
        if (res.status === 401) {
          router.replace("/admin/login");
          return;
        }
        if (!res.ok) return;
      }
      resetForm();
      await load();
    } finally {
      setSaving(false);
    }
  }

  async function remove(id: string) {
    if (!confirm("Supprimer cet ingrédient ?")) return;
    const res = await fetch(`${ADMIN_API}/ingredients/${id}`, {
      method: "DELETE",
      credentials: "include",
    });
    if (res.status === 401) {
      router.replace("/admin/login");
      return;
    }
    if (editingId === id) resetForm();
    await load();
  }

  async function logout() {
    const res = await fetch(`${ADMIN_API}/auth/logout`, {
      method: "POST",
      credentials: "include",
    });
    if (res.ok) {
      window.location.href = "/admin/login";
      return;
    }
    router.replace("/admin/login");
    router.refresh();
  }

  return (
    <div className="px-4 py-10 sm:px-6">
      <div className="mx-auto max-w-4xl">
        <div className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h1 className="text-2xl font-bold text-chocolat">Ingrédients</h1>
            <p className="text-sm text-muted">
              Créez les ingrédients réutilisables (titre, prix, photo), puis
              associez-les aux gaufres depuis le menu.
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <a
              href="/"
              target="_blank"
              rel="noopener noreferrer"
              className="rounded-full border border-chocolat/20 px-4 py-2 text-sm font-medium text-chocolat hover:bg-white"
            >
              Voir le site
            </a>
            <button
              type="button"
              onClick={() => logout()}
              className="rounded-full bg-chocolat px-4 py-2 text-sm font-medium text-cream hover:opacity-90"
            >
              Déconnexion
            </button>
          </div>
        </div>

        <form
          onSubmit={onSubmit}
          className="mb-10 rounded-[2rem] border border-chocolat/10 bg-white p-6 shadow-[0_12px_40px_-12px_rgba(61,43,31,0.12)]"
        >
          <h2 className="text-lg font-semibold text-chocolat">
            {editingId ? "Modifier l’ingrédient" : "Nouvel ingrédient"}
          </h2>
          <div className="mt-4 grid gap-4 sm:grid-cols-2">
            <label className="flex flex-col gap-1 text-sm font-medium text-chocolat sm:col-span-2">
              Titre
              <input
                value={form.name}
                onChange={(e) =>
                  setForm((f) => ({ ...f, name: e.target.value }))
                }
                required
                className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
              />
            </label>
            <label className="flex flex-col gap-1 text-sm font-medium text-chocolat">
              Prix (€)
              <input
                type="text"
                inputMode="decimal"
                value={form.price}
                onChange={(e) =>
                  setForm((f) => ({ ...f, price: e.target.value }))
                }
                required
                placeholder="0,50"
                className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 outline-none ring-gaufre/40 focus:ring-2"
              />
            </label>
            <div className="flex flex-col gap-2 sm:col-span-2">
              <span className="text-sm font-medium text-chocolat">Photo</span>
              <div className="flex flex-wrap items-end gap-3">
                <label className="inline-flex cursor-pointer items-center rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 text-sm font-medium text-chocolat hover:bg-cream">
                  <input
                    type="file"
                    accept="image/jpeg,image/png,image/webp,image/gif"
                    className="sr-only"
                    onChange={uploadFile}
                    disabled={uploading}
                  />
                  {uploading ? "Envoi…" : "Choisir un fichier"}
                </label>
                <span className="text-xs text-muted">ou colle une URL ci-dessous</span>
              </div>
              <input
                type="text"
                value={form.imageUrl}
                onChange={(e) =>
                  setForm((f) => ({ ...f, imageUrl: e.target.value }))
                }
                placeholder="https://… ou /uploads/… ou /gallery/…"
                autoComplete="off"
                className="rounded-2xl border border-chocolat/15 bg-cream/50 px-4 py-2.5 text-sm outline-none ring-gaufre/40 focus:ring-2"
              />
              {form.imageUrl.trim() ? (
                <div className="mt-2 flex items-start gap-3">
                  <div className="relative h-24 w-36 shrink-0 overflow-hidden rounded-xl border border-chocolat/10 bg-chocolat/5">
                    {form.imageUrl.startsWith("http") ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={form.imageUrl}
                        alt="Aperçu"
                        className="h-full w-full object-cover"
                      />
                    ) : (
                      <Image
                        src={form.imageUrl}
                        alt="Aperçu"
                        fill
                        unoptimized={isUploadAssetPath(form.imageUrl)}
                        className="object-cover"
                        sizes="144px"
                      />
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => setForm((f) => ({ ...f, imageUrl: "" }))}
                    className="text-sm text-red-700 underline"
                  >
                    Retirer la photo
                  </button>
                </div>
              ) : null}
            </div>
          </div>
          <div className="mt-6 flex flex-wrap gap-3">
            <button
              type="submit"
              disabled={saving || uploading}
              className="rounded-full bg-gaufre px-6 py-2.5 text-sm font-semibold text-chocolat shadow-md disabled:opacity-60"
            >
              {saving
                ? "Enregistrement…"
                : editingId
                  ? "Mettre à jour"
                  : "Ajouter"}
            </button>
            {editingId && (
              <button
                type="button"
                onClick={resetForm}
                className="rounded-full border border-chocolat/20 px-6 py-2.5 text-sm font-medium text-chocolat"
              >
                Annuler
              </button>
            )}
          </div>
        </form>

        {loading ? (
          <p className="text-muted">Chargement…</p>
        ) : (
          <ul className="space-y-3">
            {items.map((ing) => (
              <li
                key={ing.id}
                className="flex flex-col gap-3 rounded-2xl border border-chocolat/10 bg-white p-4 shadow-sm sm:flex-row sm:items-start sm:justify-between"
              >
                <div className="flex min-w-0 gap-3">
                  {ing.imageUrl ? (
                    <div className="relative h-16 w-24 shrink-0 overflow-hidden rounded-xl border border-chocolat/10 bg-chocolat/5">
                      {ing.imageUrl.startsWith("http") ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img
                          src={ing.imageUrl}
                          alt=""
                          className="h-full w-full object-cover"
                        />
                      ) : (
                        <Image
                          src={ing.imageUrl}
                          alt=""
                          fill
                          unoptimized={isUploadAssetPath(ing.imageUrl)}
                          className="object-cover"
                          sizes="96px"
                        />
                      )}
                    </div>
                  ) : null}
                  <div className="min-w-0">
                    <span className="font-semibold text-chocolat">{ing.name}</span>
                    <p className="mt-1 text-sm font-bold text-gaufre">
                      {ing.price.toFixed(2).replace(".", ",")} €
                    </p>
                  </div>
                </div>
                <div className="flex shrink-0 gap-2">
                  <button
                    type="button"
                    onClick={() => startEdit(ing)}
                    className="rounded-full border border-chocolat/20 px-4 py-1.5 text-sm font-medium text-chocolat hover:bg-cream"
                  >
                    Modifier
                  </button>
                  <button
                    type="button"
                    onClick={() => remove(ing.id)}
                    className="rounded-full border border-red-200 bg-red-50 px-4 py-1.5 text-sm font-medium text-red-800 hover:bg-red-100"
                  >
                    Supprimer
                  </button>
                </div>
              </li>
            ))}
            {items.length === 0 && (
              <li className="rounded-2xl border border-dashed border-chocolat/20 p-8 text-center text-muted">
                Aucun ingrédient pour le moment. Ajoutez-en un ci-dessus.
              </li>
            )}
          </ul>
        )}
      </div>
    </div>
  );
}
