"use client";

import { useState, useCallback } from "react";
import type { EventCartItemInput } from "@/app/actions/event-personalization";
import type { EventAddon } from "@/lib/event-addons";
import type { RecommendedProduct } from "@/app/actions/get-event-recommendations";
import type { EventType } from "@/lib/event-personalization";
import { EventThemesStep } from "./event-themes-step";
import type { EventThemeStepDraft } from "./event-theme-step";
import { EventTypeSelector } from "./event-type-selector";
import { ProductRecommendationsStep } from "./product-recommendations-step";

export interface PersonalizationState {
  eventType?: EventType;
  guestCount?: number;
  selectedProducts: RecommendedProduct[];
  selectedAddons: EventAddon[];
  themeSelections: Record<string, EventThemeStepDraft>;
}

interface Props {
  isOpen: boolean;
  onClose: () => void;
  onAddToCart?: (input: { items: EventCartItemInput[] }) => Promise<void>;
}

function createDefaultThemeDraft(product: RecommendedProduct): EventThemeStepDraft {
  const supportsThemeChoice = product.themeOptions.length > 0 && product.supportsCustomTheme !== false;

  return {
    theme: supportsThemeChoice ? product.themeOptions[0] || undefined : undefined,
    usesCustomTheme: false,
    customizations: {},
  };
}

export function EventPersonalizationModal({ isOpen, onClose, onAddToCart }: Props) {
  const [currentStep, setCurrentStep] = useState<"event" | "products" | "theme">("event");
  const [state, setState] = useState<PersonalizationState>({
    selectedProducts: [],
    selectedAddons: [],
    themeSelections: {},
  });

  const handleClose = useCallback(() => {
    setCurrentStep("event");
    setState({
      selectedProducts: [],
      selectedAddons: [],
      themeSelections: {},
    });
    onClose();
  }, [onClose]);

  const handleEventSelection = useCallback((eventType: EventType, guestCount: number) => {
    setState({
      eventType,
      guestCount,
      selectedProducts: [],
      selectedAddons: [],
      themeSelections: {},
    });
    setCurrentStep("products");
  }, []);

  const handleBack = useCallback(() => {
    if (currentStep === "theme") {
      setCurrentStep("products");
    } else if (currentStep === "products") {
      setCurrentStep("event");
    } else {
      handleClose();
    }
  }, [currentStep, handleClose]);

  const handleProductSelection = useCallback((products: RecommendedProduct[], addons: EventAddon[]) => {
    setState((prev) => {
      const themeSelections = Object.fromEntries(
        products.map((product) => [
          product.handle,
          prev.themeSelections[product.handle] || createDefaultThemeDraft(product),
        ]),
      );

      return {
        ...prev,
        selectedProducts: products,
        selectedAddons: addons,
        themeSelections,
      };
    });
    setCurrentStep("theme");
  }, []);

  const handleAddToCart = useCallback(
    async (drafts: Record<string, EventThemeStepDraft>) => {
      if (onAddToCart) {
        const addonCustomizations = Object.fromEntries(
          state.selectedAddons.map((addon) => [
            addon.id,
            {
              label: addon.label,
              value: addon.label,
              priceCents: addon.priceCents,
            },
          ]),
        );

        const items = state.selectedProducts.map((product) => {
          const draft = drafts[product.handle] || state.themeSelections[product.handle] || createDefaultThemeDraft(product);
          const mergedCustomizations = {
            ...addonCustomizations,
            ...(draft.usesCustomTheme ? draft.customizations : {}),
          };

          return {
            productHandle: product.handle,
            quantity: state.guestCount || 1,
            theme: draft.theme,
            customizations: Object.keys(mergedCustomizations).length > 0 ? mergedCustomizations : undefined,
          };
        });

        await onAddToCart({ items });
        handleClose();
      }
    },
    [handleClose, onAddToCart, state.guestCount, state.selectedAddons, state.selectedProducts, state.themeSelections]
  );

  const handleThemeDraftChange = useCallback(
    (drafts: Record<string, EventThemeStepDraft>) => {
      setState((prev) => ({
        ...prev,
        themeSelections: drafts,
      }));
    },
    [],
  );

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[9999] flex items-end md:items-center md:justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 transition-opacity"
        onClick={handleClose}
        aria-hidden="true"
      />

      {/* Modal content */}
      <div className="relative w-full max-h-[90vh] overflow-y-auto rounded-t-3xl md:rounded-2xl bg-white shadow-xl md:max-w-2xl">
        <div className="p-6 md:p-8">
          {/* Close button */}
          <button
            onClick={handleClose}
            className="absolute top-4 right-4 p-2 hover:bg-gray-100 rounded-full transition"
            aria-label="Fermer"
          >
            <svg
              className="w-6 h-6"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>

          {/* Step indicator */}
          <div className="mb-8 flex items-center justify-between">
            <div className="flex items-center gap-3">
              {[
                { key: "event", label: "Événement" },
                { key: "products", label: "Produits" },
                { key: "theme", label: "Thème" },
              ].map((step, index) => (
                <div key={step.key} className="flex items-center gap-3">
                  <div
                    className={`flex h-10 w-10 items-center justify-center rounded-full font-semibold transition ${
                      currentStep === step.key ||
                      (currentStep === "products" && step.key === "event") ||
                      (currentStep === "theme" && (step.key === "event" || step.key === "products"))
                        ? "bg-[var(--accent-3)] text-white"
                        : "bg-gray-200 text-gray-600"
                    }`}
                  >
                    {index + 1}
                  </div>
                  <span className="text-sm font-medium text-gray-600">{step.label}</span>
                  {index < 2 && (
                    <div className="h-1 w-8 bg-gray-200 mx-1" />
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Content */}
          {currentStep === "event" ? (
            <EventTypeSelector onSelect={handleEventSelection} />
          ) : currentStep === "products" ? (
            <ProductRecommendationsStep
              eventType={state.eventType!}
              guestCount={state.guestCount!}
              initialSelectedProductIds={state.selectedProducts.map((product) => product.id)}
              initialSelectedAddonIds={state.selectedAddons.map((addon) => addon.id)}
              onContinue={handleProductSelection}
            />
          ) : (
            <EventThemesStep
              products={state.selectedProducts}
              guestCount={state.guestCount!}
              selectedAddons={state.selectedAddons}
              initialDrafts={state.themeSelections}
              onDraftChange={handleThemeDraftChange}
              onSubmit={handleAddToCart}
            />
          )}

          {/* Navigation buttons */}
          <div className="mt-8 flex gap-3">
            <button
              onClick={handleBack}
              className="flex-1 rounded-full border border-[var(--accent-3)] bg-white px-6 py-3 font-semibold text-[var(--foreground)] hover:bg-gray-50 transition"
            >
              {currentStep === "event" ? "Annuler" : "Retour"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
