import { getCart, getOrCreateCart } from "@/lib/medusa/cart";
import { getCustomerTokenFromCookie, type AccountSnapshot } from "@/lib/medusa/customer";
import { env } from "@/lib/env";
import { medusa, medusaHeaders } from "@/lib/medusa/client";

export type CustomerQuoteItem = {
  line_id?: string | null;
  product_id?: string | null;
  variant_id?: string | null;
  product_title?: string | null;
  variant_title?: string | null;
  quantity?: number;
  unit_price?: number | null;
  total?: number | null;
  thumbnail?: string | null;
  metadata?: Record<string, unknown> | null;
};

export type CustomerQuote = {
  id: string;
  reference?: string | null;
  status?: string | null;
  customer_id?: string | null;
  customer_email?: string | null;
  cart_id?: string | null;
  currency_code?: string | null;
  subtotal?: number | null;
  shipping_total?: number | null;
  total?: number | null;
  event_date?: string | null;
  items?: CustomerQuoteItem[];
  cart_snapshot?: Record<string, unknown> | null;
  created_at?: string | null;
};

export type QuoteLockedPricing = {
  quote_id: string;
  reference?: string | null;
  currency_code?: string | null;
  created_at?: string | null;
  expires_at?: string | null;
  subtotal?: number | null;
  shipping_total?: number | null;
  total?: number | null;
  items?: Array<{
    quote_line_index?: number | null;
    variant_id?: string | null;
    quantity?: number | null;
    unit_price?: number | null;
    total?: number | null;
  }>;
};

export function getQuoteExpirationDate(createdAt?: string | null) {
  if (!createdAt) return null;
  const created = new Date(createdAt);
  if (Number.isNaN(created.getTime())) return null;
  const expiresAt = new Date(created);
  expiresAt.setMonth(expiresAt.getMonth() + 1);
  return expiresAt;
}

export function isQuoteExpired(createdAt?: string | null, now = new Date()) {
  const expiresAt = getQuoteExpirationDate(createdAt);
  if (!expiresAt) return true;
  return expiresAt.getTime() < now.getTime();
}

export function getActiveQuoteLockedPricing(metadata?: Record<string, unknown> | null, now = new Date()) {
  const candidate = metadata?.quote_pricing;
  if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) {
    return null;
  }

  const pricing = candidate as QuoteLockedPricing;
  const expiresAt =
    typeof pricing.expires_at === "string" && pricing.expires_at.trim()
      ? new Date(pricing.expires_at)
      : getQuoteExpirationDate(typeof pricing.created_at === "string" ? pricing.created_at : null);

  if (!expiresAt || Number.isNaN(expiresAt.getTime()) || expiresAt.getTime() < now.getTime()) {
    return null;
  }

  return pricing;
}

function buildStoreHeaders(token?: string) {
  const headers: Record<string, string> = {
    ...medusaHeaders(),
    "content-type": "application/json",
  };

  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  return headers;
}

export async function listCustomerQuotes(account: Pick<AccountSnapshot, "authenticated" | "customer">): Promise<CustomerQuote[]> {
  if (!account.authenticated || !account.customer?.id || !account.customer.email) {
    return [];
  }

  const token = await getCustomerTokenFromCookie();
  const params = new URLSearchParams({
    customer_id: account.customer.id,
    customer_email: account.customer.email,
  });

  const response = await fetch(`${env.medusaBackendUrl}/store/custom/quotes?${params.toString()}`, {
    method: "GET",
    headers: buildStoreHeaders(token || undefined),
    cache: "no-store",
  });

  if (!response.ok) {
    return [];
  }

  const payload = (await response.json()) as { quotes?: CustomerQuote[] };
  return [...(payload.quotes || [])].sort((a, b) => {
    const left = new Date(b.created_at || 0).getTime();
    const right = new Date(a.created_at || 0).getTime();
    return left - right;
  });
}

export async function getCustomerQuoteById(
  quoteId: string,
  account: Pick<AccountSnapshot, "authenticated" | "customer">,
): Promise<CustomerQuote | null> {
  const normalizedId = quoteId.trim();
  if (!normalizedId) {
    return null;
  }

  const quotes = await listCustomerQuotes(account);
  return quotes.find((quote) => quote.id === normalizedId) || null;
}

export async function saveCurrentCartAsQuote(account: Pick<AccountSnapshot, "authenticated" | "customer">) {
  if (!account.authenticated || !account.customer?.id || !account.customer.email) {
    return { ok: false, code: "not-authenticated" } as const;
  }

  const cart = await getCart();
  if (!cart || !cart.items?.length) {
    return { ok: false, code: "empty-cart" } as const;
  }

  const token = await getCustomerTokenFromCookie();
  const body = {
    customer_id: account.customer.id,
    customer_email: account.customer.email,
    cart_id: cart.id,
    currency_code: cart.currency_code || null,
    subtotal: typeof cart.subtotal === "number" ? cart.subtotal : null,
    shipping_total: typeof cart.shipping_total === "number" ? cart.shipping_total : null,
    total: typeof cart.total === "number" ? cart.total : null,
    event_date:
      typeof (cart as { metadata?: Record<string, unknown> | null }).metadata?.event_date === "string"
        ? String((cart as { metadata?: Record<string, unknown> | null }).metadata?.event_date || "")
        : null,
    items: (cart.items || []).map((item) => ({
      line_id: item.id,
      product_id: item.product_id || null,
      variant_id: item.variant_id || null,
      product_title: item.product_title || null,
      variant_title: item.variant_title || null,
      quantity: item.quantity || 1,
      unit_price: typeof item.unit_price === "number" ? item.unit_price : null,
      total: typeof item.total === "number" ? item.total : null,
      thumbnail: item.thumbnail || null,
      metadata: item.metadata && typeof item.metadata === "object" ? item.metadata : null,
    })),
    cart_snapshot: cart,
  };

  const response = await fetch(`${env.medusaBackendUrl}/store/custom/quotes`, {
    method: "POST",
    headers: buildStoreHeaders(token || undefined),
    body: JSON.stringify(body),
    cache: "no-store",
  });

  if (!response.ok) {
    return { ok: false, code: "request-failed" } as const;
  }

  const payload = (await response.json()) as { quote?: CustomerQuote };
  return { ok: true, quote: payload.quote || null } as const;
}

export async function restoreQuoteToCart(
  quoteId: string,
  account: Pick<AccountSnapshot, "authenticated" | "customer">,
) {
  if (!account.authenticated || !account.customer?.id || !account.customer.email) {
    return { ok: false, code: "not-authenticated" } as const;
  }

  const quote = await getCustomerQuoteById(quoteId, account);
  if (!quote) {
    return { ok: false, code: "not-found" } as const;
  }

  if (isQuoteExpired(quote.created_at)) {
    return { ok: false, code: "expired" } as const;
  }

  const items = Array.isArray(quote.items) ? quote.items.filter((item) => item?.variant_id && (item.quantity || 0) > 0) : [];
  if (!items.length) {
    return { ok: false, code: "empty" } as const;
  }

  const token = await getCustomerTokenFromCookie();
  const headers = buildStoreHeaders(token || undefined);
  const cart = await getOrCreateCart();

  for (const lineItem of cart.items || []) {
    await medusa.store.cart.deleteLineItem(cart.id, lineItem.id, {}, medusaHeaders());
  }

  for (const [index, item] of items.entries()) {
    await medusa.store.cart.createLineItem(
      cart.id,
      {
        variant_id: item.variant_id as string,
        quantity: Math.max(1, item.quantity || 1),
        metadata: {
          ...(item.metadata && typeof item.metadata === "object" ? item.metadata : {}),
          quote_id: quote.id,
          quote_line_index: index,
        },
      },
      {},
      medusaHeaders(),
    );
  }

  const existingCart = await getCart();
  const existingMetadata = (existingCart as { metadata?: Record<string, unknown> | null } | null)?.metadata || {};
  const nextMetadata: Record<string, unknown> = { ...existingMetadata };

  if (quote.event_date?.trim()) {
    nextMetadata.event_date = quote.event_date.trim();
  } else {
    delete nextMetadata.event_date;
  }

  nextMetadata.quote_pricing = {
    quote_id: quote.id,
    reference: quote.reference || null,
    currency_code: quote.currency_code || "eur",
    created_at: quote.created_at || null,
    expires_at: getQuoteExpirationDate(quote.created_at)?.toISOString() || null,
    subtotal: quote.subtotal ?? null,
    shipping_total: quote.shipping_total ?? null,
    total: quote.total ?? null,
    items: items.map((item, index) => ({
      quote_line_index: index,
      variant_id: item.variant_id || null,
      quantity: item.quantity || 1,
      unit_price: item.unit_price ?? null,
      total: item.total ?? null,
    })),
  } satisfies QuoteLockedPricing;

  await fetch(`${env.medusaBackendUrl}/store/carts/${cart.id}`, {
    method: "POST",
    headers,
    body: JSON.stringify({
      metadata: nextMetadata,
    }),
    cache: "no-store",
  });

  return { ok: true, quote } as const;
}

export async function deleteCustomerQuote(
  quoteId: string,
  account: Pick<AccountSnapshot, "authenticated" | "customer">,
) {
  const normalizedId = quoteId.trim();

  if (!account.authenticated || !account.customer?.id || !account.customer.email) {
    return { ok: false, code: "not-authenticated" } as const;
  }

  if (!normalizedId) {
    return { ok: false, code: "missing-id" } as const;
  }

  const token = await getCustomerTokenFromCookie();
  const params = new URLSearchParams({
    quote_id: normalizedId,
    customer_id: account.customer.id,
    customer_email: account.customer.email,
  });

  const response = await fetch(`${env.medusaBackendUrl}/store/custom/quotes?${params.toString()}`, {
    method: "DELETE",
    headers: buildStoreHeaders(token || undefined),
    cache: "no-store",
  });

  if (response.status === 404) {
    return { ok: false, code: "not-found" } as const;
  }

  if (!response.ok) {
    return { ok: false, code: "request-failed" } as const;
  }

  return { ok: true } as const;
}
