"use client";

import Image from "next/image";
import { useState, useEffect } from "react";
import { getEventRecommendedProducts } from "@/app/actions/get-event-recommendations";
import type { RecommendedProduct } from "@/app/actions/get-event-recommendations";
import { getEventAddons, type EventAddon } from "@/lib/event-addons";
import type { EventType } from "@/lib/event-personalization";

interface Props {
  eventType: EventType;
  guestCount: number;
  initialSelectedProductIds?: string[];
  initialSelectedAddonIds?: string[];
  onContinue: (products: RecommendedProduct[], addons: EventAddon[]) => void;
}

export function ProductRecommendationsStep({
  eventType,
  guestCount,
  initialSelectedProductIds = [],
  initialSelectedAddonIds = [],
  onContinue,
}: Props) {
  const [products, setProducts] = useState<RecommendedProduct[]>([]);
  const [addons, setAddons] = useState<EventAddon[]>([]);
  const [selectedProductIds, setSelectedProductIds] = useState<Set<string>>(new Set());
  const [selectedAddons, setSelectedAddons] = useState<Set<string>>(new Set());
  const [isLoadingProducts, setIsLoadingProducts] = useState(true);
  const [submitError, setSubmitError] = useState<string | null>(null);

  // Load recommended products and addons for this event type
  useEffect(() => {
    const loadData = async () => {
      setIsLoadingProducts(true);
      try {
        const [recommendedProducts, eventAddons] = await Promise.all([
          getEventRecommendedProducts(eventType),
          Promise.resolve(getEventAddons(eventType)),
        ]);

        setProducts(recommendedProducts);
        setAddons(eventAddons);
        setSelectedAddons(new Set(initialSelectedAddonIds));
        setSubmitError(null);
        setSelectedProductIds((current) => {
          const validCurrentIds = Array.from(current).filter((id) =>
            recommendedProducts.some((product) => product.id === id),
          );
          if (validCurrentIds.length > 0) {
            return new Set(validCurrentIds);
          }

          const validInitialIds = initialSelectedProductIds.filter((id) =>
            recommendedProducts.some((product) => product.id === id),
          );
          if (validInitialIds.length > 0) {
            return new Set(validInitialIds);
          }

          return recommendedProducts[0]?.id ? new Set([recommendedProducts[0].id]) : new Set();
        });
      } catch (error) {
        console.error("Error loading event recommendations:", error);
        setProducts([]);
        setAddons([]);
        setSelectedProductIds(new Set());
        setSelectedAddons(new Set());
        setSubmitError("Impossible de charger les recommandations pour le moment.");
      } finally {
        setIsLoadingProducts(false);
      }
    };

    loadData();
  }, [eventType, initialSelectedAddonIds, initialSelectedProductIds]);

  const handleProductToggle = (productId: string) => {
    setSelectedProductIds((current) => {
      const next = new Set(current);
      if (next.has(productId)) {
        next.delete(productId);
      } else {
        next.add(productId);
      }
      return next;
    });
    setSubmitError(null);
  };

  const handleAddonToggle = (addonId: string) => {
    const newAddons = new Set(selectedAddons);
    if (newAddons.has(addonId)) {
      newAddons.delete(addonId);
    } else {
      newAddons.add(addonId);
    }
    setSelectedAddons(newAddons);
    setSubmitError(null);
  };

  const handleContinue = () => {
    if (selectedProducts.length === 0) {
      setSubmitError("Veuillez sélectionner au moins un produit.");
      return;
    }

    setSubmitError(null);
    onContinue(
      selectedProducts,
      addons.filter((addon) => selectedAddons.has(addon.id)),
    );
  };

  const selectedProducts = products.filter((product) => selectedProductIds.has(product.id));
  const selectedAddonsTotal = Array.from(selectedAddons).reduce((acc, addonId) => {
    const addon = addons.find((a) => a.id === addonId);
    return acc + (addon?.priceCents || 0);
  }, 0);

  const productsSubtotal = selectedProducts.reduce(
    (total, product) => total + (product.salePriceCents || product.priceCents) * guestCount,
    0,
  );
  const addonsSubtotal = selectedProducts.length * selectedAddonsTotal * guestCount;
  const totalPrice = productsSubtotal + addonsSubtotal;

  return (
    <div className="space-y-6">
      <div>
        <h2 className="font-serif text-2xl text-[var(--foreground)] mb-2">
          Produits recommandés
        </h2>
        
        {isLoadingProducts ? (
          <p className="text-sm text-[var(--muted)]">Chargement des produits...</p>
        ) : (
          <>
            <p className="text-sm text-[var(--muted)] mb-6">
              Nous avons sélectionné {products.length} produit
              {products.length !== 1 ? "s" : ""} parfait
              {products.length !== 1 ? "s" : ""} pour votre événement
            </p>
            <p className="mb-6 rounded-2xl border border-[var(--line)] bg-[#faf7f5] px-4 py-3 text-sm text-[var(--muted)]">
              {selectedProducts.length} produit{selectedProducts.length > 1 ? "s" : ""} sélectionné
              {selectedProducts.length > 1 ? "s" : ""}.
            </p>

            {products.length > 0 ? (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
                {products.map((product) => (
                  <button
                    key={product.id}
                    onClick={() => {
                      handleProductToggle(product.id);
                    }}
                    className={`text-left rounded-xl border-2 p-4 transition ${
                      selectedProductIds.has(product.id)
                        ? "border-[var(--accent-3)] bg-[#fff0f0]"
                        : "border-[#e5e5e5] bg-white hover:border-[var(--accent-3)]"
                    }`}
                  >
                    {product.imageUrl && (
                      <div className="mb-3 bg-gray-100 rounded-lg overflow-hidden relative h-32">
                        <Image
                          src={product.imageUrl}
                          alt={product.title}
                          fill
                          className="object-cover"
                          sizes="(max-width: 768px) 100vw, 50vw"
                        />
                      </div>
                    )}
                    <p className="font-semibold text-[var(--foreground)]">{product.title}</p>
                    <p className="mt-1 text-xs font-medium text-[var(--accent-3)]">
                      {selectedProductIds.has(product.id) ? "Sélectionné" : "Cliquer pour ajouter"}
                    </p>
                    <p className="text-xs text-[var(--muted)] mb-2">
                      {product.salePriceCents && product.regularPriceCents ? (
                        <>
                          <span className="line-through">
                            {(product.regularPriceCents / 100).toFixed(2)}€
                          </span>
                          {" "}
                        </>
                      ) : null}
                    </p>
                    <p className="font-bold text-[var(--accent-3)]">
                      {((product.salePriceCents || product.priceCents) / 100).toFixed(2)}€
                    </p>
                  </button>
                ))}
              </div>
            ) : (
              <div className="mb-8 rounded-2xl border border-[var(--line)] bg-[#faf7f5] p-5 text-sm text-[var(--muted)]">
                Aucun produit n&apos;est disponible pour cette sélection pour le moment.
              </div>
            )}

            {/* Addons */}
            {addons.length > 0 && (
              <div className="mb-8">
                <h3 className="font-semibold text-[var(--foreground)] mb-4">
                  Ajouter des suppléments
                </h3>
                <p className="mb-4 text-xs text-[var(--muted)]">
                  Les suppléments sélectionnés seront appliqués à chaque produit choisi.
                </p>
                <div className="space-y-3">
                  {addons.map((addon) => (
                    <label
                      key={addon.id}
                      className="flex items-center gap-3 p-4 rounded-lg border border-[#e5e5e5] hover:bg-gray-50 cursor-pointer transition"
                    >
                      <input
                        type="checkbox"
                        checked={selectedAddons.has(addon.id)}
                        onChange={() => handleAddonToggle(addon.id)}
                        className="w-5 h-5 rounded border-[var(--accent-3)] text-[var(--accent-3)] cursor-pointer"
                      />
                      <div className="flex-1">
                        <p className="font-medium text-[var(--foreground)]">{addon.label}</p>
                        <p className="text-xs text-[var(--muted)]">
                          +{(addon.priceCents / 100).toFixed(2)}€
                        </p>
                      </div>
                    </label>
                  ))}
                </div>
              </div>
            )}

            {/* Price summary */}
            <div className="rounded-lg bg-[#f5f5f5] p-4 mb-6">
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-[var(--muted)]">
                    Produits ({selectedProducts.length}) × {guestCount}
                  </span>
                  <span className="font-semibold text-[var(--foreground)]">
                    {(productsSubtotal / 100).toFixed(2)}€
                  </span>
                </div>
                {addonsSubtotal > 0 && (
                  <div className="flex justify-between text-sm">
                    <span className="text-[var(--muted)]">Suppléments</span>
                    <span className="font-semibold text-[var(--foreground)]">
                      {(addonsSubtotal / 100).toFixed(2)}€
                    </span>
                  </div>
                )}
                <div className="border-t border-[#ddd] pt-2 flex justify-between">
                  <span className="font-bold text-[var(--foreground)]">Total</span>
                  <span className="font-bold text-[var(--accent-3)] text-lg">
                    {(totalPrice / 100).toFixed(2)}€
                  </span>
                </div>
              </div>
            </div>

            {submitError ? (
              <div className="mb-6 rounded-lg border border-[#ffd4d4] bg-[#fff5f5] p-4 text-sm text-[#a21717]">
                {submitError}
              </div>
            ) : null}
          </>
        )}
      </div>

      {/* Next button */}
      <button
        onClick={handleContinue}
        disabled={selectedProductIds.size === 0 || isLoadingProducts}
        className="w-full rounded-full bg-[var(--accent-3)] px-6 py-3 font-semibold text-white hover:bg-[var(--accent-2)] transition disabled:opacity-50 disabled:cursor-not-allowed"
      >
        {selectedProductIds.size > 1 ? `Suivant (${selectedProductIds.size} produits)` : "Suivant"}
      </button>
    </div>
  );
}
