"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import {
  addToCart,
  applyPromoCode,
  getCart,
  removeLineItem,
  removePromoCode,
  transferCurrentCartToCustomer,
  updateCartMondialRelayPoint,
  updateCartEventDate,
  updateCartOrderNote,
  updateCartShippingOption,
  updateLineItemQuantity,
} from "@/lib/medusa/cart";
import { env } from "@/lib/env";
import { getStripeServerClient, isStripeConfigured } from "@/lib/stripe";
import { getEffectiveCartTotal, getEffectiveShippingTotal } from "@/lib/utils/cart-pricing";
import { getAccountSnapshot, getCustomerAuthState, getCustomerTokenFromCookie } from "@/lib/medusa/customer";
import { deleteCustomerQuote, getActiveQuoteLockedPricing, restoreQuoteToCart, saveCurrentCartAsQuote } from "@/lib/medusa/quotes";
import {
  getMondialRelayPointFromCart,
  isMondialRelayShippingMethod,
  sanitizeMondialRelayPoint,
} from "@/lib/mondial-relay";
import { getMondialRelayQuote } from "@/lib/mondial-relay-pricing";
import { isLocalPickupShippingMethod } from "@/lib/local-pickup";
import { getLineItemCustomizationSurchargeTotalCents } from "@/lib/personalization-pricing";

const PAYMENT_AUTH_REDIRECT = "/connexion?notice=checkout-login-required&next=%2Fpanier%3Fstep%3D3";

export async function addToCartAction(formData: FormData) {
  const variantId = String(formData.get("variantId") || "");
  const quantity = Number(formData.get("quantity") || 1);
  const theme = String(formData.get("theme") || "");
  const paperFinish = String(formData.get("paperFinish") || "");
  const personalization = String(formData.get("personalization") || "");
  const customizationsRaw = String(formData.get("customizations") || "");
  const returnTo = String(formData.get("returnTo") || "/panier");
  const customizations =
    customizationsRaw.trim()
      ? (() => {
          try {
            const parsed = JSON.parse(customizationsRaw) as unknown;
            return parsed && typeof parsed === "object" && !Array.isArray(parsed)
              ? (parsed as Record<string, { label?: string; value?: string; priceCents?: number }>)
              : undefined;
          } catch {
            return undefined;
          }
        })()
      : undefined;

  if (!variantId) {
    return;
  }

  await addToCart({ variantId, quantity, personalization, theme, paperFinish, customizations });
  revalidatePath("/panier");
  revalidatePath("/", "layout");

  if (!returnTo.startsWith("/")) {
    redirect("/panier?openCart=1");
  }

  const [path, query = ""] = returnTo.split("?");
  const params = new URLSearchParams(query);
  params.set("openCart", "1");
  const nextUrl = `${path}?${params.toString()}`;

  redirect(nextUrl);
}

export async function updateCartEventDateAction(formData: FormData) {
  const eventDate = String(formData.get("eventDate") || "");
  const result = await updateCartEventDate(eventDate || null);

  if (result.ok) {
    revalidatePath("/panier");
    revalidatePath("/", "layout");
  }

  return result;
}

export async function submitCartEventDateAction(formData: FormData) {
  await updateCartEventDateAction(formData);
}

export async function updateCartOrderNoteAction(formData: FormData) {
  const orderNote = String(formData.get("orderNote") || "");
  const result = await updateCartOrderNote(orderNote || null);

  if (result.ok) {
    revalidatePath("/panier");
    revalidatePath("/", "layout");
  }

  return result;
}

export async function updateLineItemAction(formData: FormData) {
  const lineId = String(formData.get("lineId") || "");
  const quantity = Number(formData.get("quantity") || 1);

  if (!lineId) {
    return;
  }

  await updateLineItemQuantity(lineId, quantity);
  revalidatePath("/panier");
  revalidatePath("/", "layout");
}

export async function removeLineItemAction(formData: FormData) {
  const lineId = String(formData.get("lineId") || "");

  if (!lineId) {
    return;
  }

  await removeLineItem(lineId);
  revalidatePath("/panier");
  revalidatePath("/", "layout");
}

export async function applyPromoCodeAction(formData: FormData) {
  const code = String(formData.get("code") || "");
  const result = await applyPromoCode(code);

  if (result.ok) {
    revalidatePath("/panier");
    revalidatePath("/", "layout");
  }

  return result;
}

export async function removePromoCodeAction(formData: FormData) {
  const code = String(formData.get("code") || "");
  const result = await removePromoCode(code);

  if (result.ok) {
    revalidatePath("/panier");
    revalidatePath("/", "layout");
  }

  return result;
}

export async function setMondialRelayPickupAction(formData: FormData) {
  const point = sanitizeMondialRelayPoint({
    id: String(formData.get("id") || ""),
    name: String(formData.get("name") || ""),
    address1: String(formData.get("address1") || ""),
    address2: String(formData.get("address2") || ""),
    postalCode: String(formData.get("postalCode") || ""),
    city: String(formData.get("city") || ""),
    countryCode: String(formData.get("countryCode") || "FR"),
  });

  if (!point) {
    return { ok: false, message: "Point Relais invalide." };
  }

  const result = await updateCartMondialRelayPoint(point);

  if (result.ok) {
    revalidatePath("/panier");
    revalidatePath("/", "layout");
  }

  return result;
}

export async function clearMondialRelayPickupAction() {
  const result = await updateCartMondialRelayPoint(null);

  if (result.ok) {
    revalidatePath("/panier");
    revalidatePath("/", "layout");
  }

  return result;
}

export async function updateShippingOptionAction(formData: FormData) {
  const optionId = String(formData.get("optionId") || "");
  const result = await updateCartShippingOption(optionId);

  if (result.ok) {
    const cart = await getCart();
    if (cart && !isMondialRelayShippingMethod(cart) && getMondialRelayPointFromCart(cart)) {
      await updateCartMondialRelayPoint(null);
    }
    revalidatePath("/panier");
    revalidatePath("/", "layout");
  }
}

export async function startStripeCheckoutAction() {
  const account = await getCustomerAuthState();

  if (!account.authenticated) {
    redirect(PAYMENT_AUTH_REDIRECT);
  }

  if (!isStripeConfigured()) {
    redirect("/panier?stripe=config-missing");
  }

  const customerToken = await getCustomerTokenFromCookie();
  if (customerToken) {
    await transferCurrentCartToCustomer(customerToken);
  }

  const cart = await getCart();

  if (!cart || !cart.items?.length) {
    redirect("/panier?stripe=empty-cart");
  }

  const quoteLockedPricing = getActiveQuoteLockedPricing(
    (cart as { metadata?: Record<string, unknown> | null }).metadata || null,
  );
  const cartCustomizationSurchargeCents = (cart.items || []).reduce(
    (total, item) => total + getLineItemCustomizationSurchargeTotalCents({ quantity: item.quantity || 1, metadata: item.metadata || null }),
    0,
  );
  const adjustedSubtotal = typeof cart.subtotal === "number" ? cart.subtotal + cartCustomizationSurchargeCents : cart.subtotal;
  const adjustedCartTotal = typeof cart.total === "number" ? cart.total + cartCustomizationSurchargeCents : cart.total;

  const total = quoteLockedPricing?.total ?? getEffectiveCartTotal({
    subtotal: adjustedSubtotal,
    shippingTotal: cart.shipping_total,
    total: adjustedCartTotal,
  });

  if (typeof total !== "number" || total <= 0) {
    redirect("/panier?stripe=invalid-total");
  }

  const shippingTotal = quoteLockedPricing?.shipping_total ?? getEffectiveShippingTotal({
    subtotal: adjustedSubtotal,
    shippingTotal: cart.shipping_total,
  });

  const usesMondialRelay = isMondialRelayShippingMethod(cart);
  const usesLocalPickup = isLocalPickupShippingMethod(cart);
  const relayPoint = getMondialRelayPointFromCart(cart);
  const cartEventDate =
    typeof (cart as { metadata?: Record<string, unknown> | null }).metadata?.event_date === "string"
      ? String((cart as { metadata?: Record<string, unknown> | null }).metadata?.event_date || "")
      : "";

  if (usesMondialRelay && !relayPoint) {
    redirect("/panier?stripe=relay-missing");
  }

  let effectiveShippingTotal = shippingTotal;
  let effectiveTotal = total;

  if (usesLocalPickup) {
    effectiveShippingTotal = 0;

    if (typeof shippingTotal === "number") {
      effectiveTotal = Math.max(0, total - shippingTotal);
    }
  }

  if (usesMondialRelay) {
    const relayQuote = getMondialRelayQuote(cart);
    if (relayQuote.amount === null) {
      redirect("/panier?stripe=relay-unavailable");
    }

    effectiveShippingTotal = relayQuote.amount;

    if (typeof shippingTotal === "number") {
      effectiveTotal = Math.max(0, total - shippingTotal + relayQuote.amount);
    }
  }

  const currency = (cart.currency_code || "eur").toLowerCase();
  const stripe = getStripeServerClient();

  const lockedItemsByIndex = new Map(
    (quoteLockedPricing?.items || [])
      .filter((item) => typeof item?.quote_line_index === "number")
      .map((item) => [Number(item.quote_line_index), item]),
  );

  const lineItems = (cart.items || [])
    .map((item) => {
      const quantity = Math.max(1, item.quantity || 1);
      const lockedItem =
        typeof item.metadata?.quote_line_index === "number"
          ? lockedItemsByIndex.get(Number(item.metadata.quote_line_index))
          : null;
      const itemTotal =
        typeof lockedItem?.total === "number"
          ? lockedItem.total
          : typeof item.total === "number"
            ? item.total
            : 0;
      const unitAmount =
        typeof lockedItem?.unit_price === "number"
          ? Math.max(0, lockedItem.unit_price)
          : Math.max(0, Math.round(itemTotal / quantity));
      const customizationSurchargePerUnit =
        Math.round(getLineItemCustomizationSurchargeTotalCents({ quantity, metadata: item.metadata || null }) / quantity) || 0;
      const finalUnitAmount = unitAmount + customizationSurchargePerUnit;

      if (finalUnitAmount <= 0) {
        return null;
      }

      return {
        quantity,
        price_data: {
          currency,
          unit_amount: finalUnitAmount,
          product_data: {
            name: item.product_title || "Produit Stylunique",
          },
        },
      };
    })
    .filter(Boolean) as Array<{
    quantity: number;
    price_data: {
      currency: string;
      unit_amount: number;
      product_data: {
        name: string;
      };
    };
  }>;

  if (typeof effectiveShippingTotal === "number" && effectiveShippingTotal > 0) {
    lineItems.push({
      quantity: 1,
      price_data: {
        currency,
        unit_amount: effectiveShippingTotal,
        product_data: {
          name: "Livraison",
        },
      },
    });
  }

  const lineItemsTotal = lineItems.reduce((sum, item) => sum + item.price_data.unit_amount * item.quantity, 0);
  const normalizedLineItems =
    lineItems.length > 0 && lineItemsTotal === effectiveTotal
      ? lineItems
      : [
          {
            quantity: 1,
            price_data: {
              currency,
              unit_amount: effectiveTotal,
              product_data: {
                name: "Commande Stylunique",
              },
            },
          },
        ];

  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    line_items: normalizedLineItems,
    success_url: `${env.siteUrl}/api/stripe/success?session_id={CHECKOUT_SESSION_ID}`,
    cancel_url: `${env.siteUrl}/panier?stripe=cancelled`,
    metadata: {
      source: "storefront",
      medusa_cart_id: cart.id,
      mondial_relay_point_id: relayPoint?.id || "",
      mondial_relay_name: relayPoint?.name || "",
      mondial_relay_shipping_amount: usesMondialRelay && typeof effectiveShippingTotal === "number" ? String(effectiveShippingTotal) : "",
      local_pickup: usesLocalPickup ? "true" : "",
      local_pickup_label: usesLocalPickup ? env.localPickupLabel : "",
      local_pickup_address: usesLocalPickup ? env.localPickupAddress : "",
      event_date: cartEventDate,
    },
  });

  if (!session.url) {
    redirect("/panier?stripe=checkout-error");
  }

  redirect(session.url);
}

export async function saveCartAsQuoteAction() {
  const account = await getAccountSnapshot();

  if (!account.authenticated || !account.customer) {
    redirect("/connexion?next=%2Fpanier");
  }

  const result = await saveCurrentCartAsQuote(account);

  if (!result.ok) {
    if (result.code === "empty-cart") {
      redirect("/panier?quote=empty");
    }

    redirect("/panier?quote=error");
  }

  revalidatePath("/compte");
  revalidatePath("/panier");
  redirect("/compte?notice=quote-saved&section=quotes#mes-devis");
}

export async function restoreQuoteToCartAction(formData: FormData) {
  const quoteId = String(formData.get("quoteId") || "").trim();
  const account = await getAccountSnapshot();

  const result = await restoreQuoteToCart(quoteId, account);

  if (!result.ok) {
    if (result.code === "expired") {
      redirect("/panier?quote=expired");
    }

    redirect("/panier?quote=error");
  }

  revalidatePath("/panier");
  revalidatePath("/", "layout");
  redirect("/panier?quote=restored&openCart=1");
}

export async function deleteQuoteAction(formData: FormData) {
  const quoteId = String(formData.get("quoteId") || "").trim();
  const account = await getAccountSnapshot();

  const result = await deleteCustomerQuote(quoteId, account);

  if (!result.ok) {
    redirect("/compte/devis");
  }

  revalidatePath("/compte");
  revalidatePath("/compte/devis");
  redirect("/compte/devis");
}
