"use client";

import { useMemo, useState } from "react";
import { ProductActions } from "@/components/admin/product-actions";

type Product = {
  id: string;
  name: string;
  description: string | null;
  price: number;
  image: string | null;
  isAvailable: boolean;
  isFeatured: boolean;
  categoryId: string;
};

type Category = {
  id: string;
  name: string;
  description: string | null;
  products: Product[];
};

export function MenuManager({
  categories,
}: {
  categories: Category[];
}) {
  const [search, setSearch] = useState("");
  const [categoryId, setCategoryId] = useState("ALL");
  const [availability, setAvailability] =
    useState("ALL");
  const [featured, setFeatured] =
    useState("ALL");

  const filteredCategories = useMemo(() => {
    const searchValue =
      search.trim().toLowerCase();

    return categories
      .map((category) => {
        const products =
          category.products.filter((product) => {
            const matchesSearch =
              !searchValue ||
              product.name
                .toLowerCase()
                .includes(searchValue) ||
              product.description
                ?.toLowerCase()
                .includes(searchValue);

            const matchesCategory =
              categoryId === "ALL" ||
              category.id === categoryId;

            const matchesAvailability =
              availability === "ALL" ||
              (availability === "AVAILABLE" &&
                product.isAvailable) ||
              (availability === "UNAVAILABLE" &&
                !product.isAvailable);

            const matchesFeatured =
              featured === "ALL" ||
              (featured === "FEATURED" &&
                product.isFeatured) ||
              (featured === "NOT_FEATURED" &&
                !product.isFeatured);

            return (
              matchesSearch &&
              matchesCategory &&
              matchesAvailability &&
              matchesFeatured
            );
          });

        return {
          ...category,
          products,
        };
      })
      .filter(
        (category) =>
          category.products.length > 0
      );
  }, [
    categories,
    search,
    categoryId,
    availability,
    featured,
  ]);

  const totalProducts =
    filteredCategories.reduce(
      (total, category) =>
        total + category.products.length,
      0
    );

  function resetFilters() {
    setSearch("");
    setCategoryId("ALL");
    setAvailability("ALL");
    setFeatured("ALL");
  }

  async function toggleAvailability(
    productId: string,
    currentAvailability: boolean
  ) {
    try {
      const response = await fetch(
        `/api/products/${productId}`,
        {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            isAvailable:
              !currentAvailability,
          }),
        }
      );

      const result = await response.json();

      if (!response.ok) {
        throw new Error(
          result.message ||
            "Impossible de modifier la disponibilité."
        );
      }

      window.location.reload();
    } catch (error) {
      console.error(
        "Erreur modification disponibilité :",
        error
      );

      alert(
        error instanceof Error
          ? error.message
          : "Une erreur est survenue."
      );
    }
  }

  return (
    <div className="space-y-6">
      {/* FILTRES */}
      <div className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm">
        <div className="mb-5">
          <p className="text-sm font-semibold uppercase tracking-[0.2em] text-[#a68b5b]">
            Recherche et filtres
          </p>

          <h2 className="mt-1 text-xl font-bold">
            Gérer les produits
          </h2>

          <p className="mt-2 text-sm text-gray-500">
            Recherchez et filtrez rapidement les
            produits du menu.
          </p>
        </div>

        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {/* RECHERCHE */}
          <div className="lg:col-span-2">
            <label
              htmlFor="menu-search"
              className="mb-2 block text-sm font-semibold"
            >
              Rechercher un produit
            </label>

            <input
              id="menu-search"
              type="search"
              value={search}
              onChange={(event) =>
                setSearch(event.target.value)
              }
              placeholder="Ex : poulet, poisson..."
              className="w-full rounded-xl border border-gray-200 px-4 py-3 outline-none transition focus:border-[#b8863b]"
            />
          </div>

          {/* CATÉGORIE */}
          <div>
            <label
              htmlFor="menu-category"
              className="mb-2 block text-sm font-semibold"
            >
              Catégorie
            </label>

            <select
              id="menu-category"
              value={categoryId}
              onChange={(event) =>
                setCategoryId(event.target.value)
              }
              className="w-full rounded-xl border border-gray-200 bg-white px-4 py-3 outline-none transition focus:border-[#b8863b]"
            >
              <option value="ALL">
                Toutes les catégories
              </option>

              {categories.map((category) => (
                <option
                  key={category.id}
                  value={category.id}
                >
                  {category.name}
                </option>
              ))}
            </select>
          </div>

          {/* DISPONIBILITÉ */}
          <div>
            <label
              htmlFor="menu-availability"
              className="mb-2 block text-sm font-semibold"
            >
              Disponibilité
            </label>

            <select
              id="menu-availability"
              value={availability}
              onChange={(event) =>
                setAvailability(
                  event.target.value
                )
              }
              className="w-full rounded-xl border border-gray-200 bg-white px-4 py-3 outline-none transition focus:border-[#b8863b]"
            >
              <option value="ALL">
                Tous
              </option>

              <option value="AVAILABLE">
                Disponibles
              </option>

              <option value="UNAVAILABLE">
                Indisponibles
              </option>
            </select>
          </div>
        </div>

        <div className="mt-4 flex flex-col gap-4 sm:flex-row sm:items-end">
          {/* À LA UNE */}
          <div className="w-full sm:max-w-xs">
            <label
              htmlFor="menu-featured"
              className="mb-2 block text-sm font-semibold"
            >
              Mise à la une
            </label>

            <select
              id="menu-featured"
              value={featured}
              onChange={(event) =>
                setFeatured(
                  event.target.value
                )
              }
              className="w-full rounded-xl border border-gray-200 bg-white px-4 py-3 outline-none transition focus:border-[#b8863b]"
            >
              <option value="ALL">
                Tous
              </option>

              <option value="FEATURED">
                À la une
              </option>

              <option value="NOT_FEATURED">
                Pas à la une
              </option>
            </select>
          </div>

          {/* COMPTEUR */}
          <div className="rounded-xl bg-[#f8f6f1] px-5 py-3 text-sm text-gray-600">
            <strong className="text-gray-900">
              {totalProducts}
            </strong>{" "}
            produit
            {totalProducts > 1 ? "s" : ""} affiché
            {totalProducts > 1 ? "s" : ""}
          </div>

          {/* RESET */}
          <button
            type="button"
            onClick={resetFilters}
            className="rounded-full border border-gray-200 px-5 py-3 text-sm font-semibold transition hover:bg-gray-50"
          >
            Réinitialiser
          </button>
        </div>
      </div>

      {/* RÉSULTATS */}
      {filteredCategories.length === 0 ? (
        <div className="rounded-2xl border border-[#e8e1d6] bg-white p-12 text-center shadow-sm">
          <h2 className="text-xl font-bold">
            Aucun produit trouvé
          </h2>

          <p className="mt-2 text-sm text-gray-500">
            Essayez de modifier votre recherche ou
            vos filtres.
          </p>
        </div>
      ) : (
        <div className="space-y-6">
          {filteredCategories.map((category) => (
            <section
              key={category.id}
              className="rounded-2xl border border-[#e8e1d6] bg-white p-6 shadow-sm"
            >
              {/* CATÉGORIE */}
              <div className="mb-6 flex flex-col justify-between gap-4 border-b border-[#eee8df] pb-5 sm:flex-row sm:items-center">
                <div>
                  <h2 className="text-xl font-bold">
                    {category.name}
                  </h2>

                  {category.description && (
                    <p className="mt-1 text-sm text-gray-500">
                      {category.description}
                    </p>
                  )}
                </div>

                <span className="rounded-full bg-[#f5efe5] px-4 py-2 text-xs font-semibold text-[#8d754e]">
                  {category.products.length} produit
                  {category.products.length > 1
                    ? "s"
                    : ""}
                </span>
              </div>

              {/* PRODUITS */}
              <div className="grid gap-4 md:grid-cols-2">
                {category.products.map((product) => (
                  <article
                    key={product.id}
                    className="rounded-2xl border border-[#eee8df] p-5 transition hover:shadow-md"
                  >
                    <div className="flex items-start justify-between gap-4">
                      <div className="min-w-0">
                        <h3 className="text-lg font-bold">
                          {product.name}
                        </h3>

                        {product.description && (
                          <p className="mt-2 text-sm leading-6 text-gray-500">
                            {product.description}
                          </p>
                        )}
                      </div>

                      <span className="whitespace-nowrap font-bold text-[#a68b5b]">
                        {new Intl.NumberFormat(
                          "fr-FR"
                        ).format(product.price)}{" "}
                        FCFA
                      </span>
                    </div>

                    {product.image && (
                      <div className="mt-4">
                        <img
                          src={product.image}
                          alt={product.name}
                          className="h-40 w-full rounded-xl object-cover"
                        />
                      </div>
                    )}

                    <div className="mt-5 flex flex-wrap items-center gap-2">
                      {/* BOUTON DISPONIBILITÉ */}
                      <button
                        type="button"
                        onClick={() =>
                          toggleAvailability(
                            product.id,
                            product.isAvailable
                          )
                        }
                        className={`rounded-full px-3 py-1 text-xs font-semibold transition ${
                          product.isAvailable
                            ? "bg-green-100 text-green-700 hover:bg-green-200"
                            : "bg-red-100 text-red-700 hover:bg-red-200"
                        }`}
                        title="Cliquer pour modifier la disponibilité"
                      >
                        {product.isAvailable
                          ? "🟢 Disponible"
                          : "🔴 Indisponible"}
                      </button>

                      {/* À LA UNE */}
                      {product.isFeatured && (
                        <span className="rounded-full bg-yellow-100 px-3 py-1 text-xs font-semibold text-yellow-700">
                          ⭐ À la une
                        </span>
                      )}
                    </div>

                    {/* ACTIONS */}
                    <ProductActions
                      product={{
                        id: product.id,
                        name: product.name,
                        description:
                          product.description,
                        price: product.price,
                        image: product.image,
                        isAvailable:
                          product.isAvailable,
                        isFeatured:
                          product.isFeatured,
                        categoryId:
                          product.categoryId,
                      }}
                      categories={categories.map(
                        (category) => ({
                          id: category.id,
                          name: category.name,
                        })
                      )}
                    />
                  </article>
                ))}
              </div>
            </section>
          ))}
        </div>
      )}
    </div>
  );
}
