"use client";

import { ReactNode, useMemo, type KeyboardEvent } from "react";
import { StatusPill } from "@/components/atoms/status-pill";
import {
  calculateOrderTotals,
  deriveOrderStatusDescriptor,
  getServiceCategory,
} from "@/features/orders/utils/order-presenters";
import { buildOrderDisplayItems } from "@/features/orders/utils/order-display";
import { OrderServiceIcon } from "@/features/orders/components/OrderServiceIcon";
import type { OrderSummary } from "@customer-portal/domain/orders";
import { cn } from "@/shared/utils";

export type OrderSummaryLike = OrderSummary & { itemSummary?: string };

export type OrderCardVariant = "standalone" | "list";

export interface OrderCardProps {
  order: OrderSummaryLike;
  onClick?: () => void;
  footer?: ReactNode;
  className?: string;
  /** Visual variant: "standalone" (default) has border/shadow, "list" works inside divide-y container */
  variant?: OrderCardVariant;
}

const STATUS_PILL_VARIANT = {
  success: "success",
  info: "info",
  warning: "warning",
  neutral: "neutral",
} as const;

const SERVICE_ICON_STYLES = {
  internet: "bg-info/10 text-info border border-info/10",
  sim: "bg-primary/10 text-primary border border-primary/10",
  vpn: "bg-success/10 text-success border border-success/10",
  default: "bg-muted text-muted-foreground border border-border",
} as const;

export function OrderCard({
  order,
  onClick,
  footer,
  className,
  variant = "standalone",
}: OrderCardProps) {
  const statusDescriptor = deriveOrderStatusDescriptor({
    status: order.status,
    activationStatus: order.activationStatus ?? "",
  });
  const statusVariant = STATUS_PILL_VARIANT[statusDescriptor.tone];
  const serviceCategory = getServiceCategory(order.orderType);
  const iconStyles = SERVICE_ICON_STYLES[serviceCategory];
  const serviceIcon = <OrderServiceIcon orderType={order.orderType ?? ""} />;
  const displayItems = useMemo(
    () => buildOrderDisplayItems(order.itemsSummary),
    [order.itemsSummary]
  );

  // Use just the order type as the service name
  const serviceName = order.orderType ? `${order.orderType} Service` : "Service Order";

  const totals = calculateOrderTotals(order.itemsSummary, order.totalAmount);
  const createdDate = useMemo(() => {
    if (!order.createdDate) return null;
    const parsed = new Date(order.createdDate);
    return Number.isNaN(parsed.getTime()) ? null : parsed;
  }, [order.createdDate]);
  const formattedCreatedDate = useMemo(() => {
    if (!createdDate) return "—";
    return new Intl.DateTimeFormat("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    }).format(createdDate);
  }, [createdDate]);
  const isInteractive = typeof onClick === "function";
  const showPricing = totals.monthlyTotal > 0 || totals.oneTimeTotal > 0;

  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (!isInteractive) return;
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault();
      onClick?.();
    }
  };

  const isListVariant = variant === "list";

  return (
    <article
      key={String(order.id)}
      className={cn(
        "group overflow-hidden bg-card transition-all duration-200 focus-visible:outline-none",
        // Standalone variant: full card styling with border, shadow, rounded corners
        !isListVariant && "rounded-2xl border border-border shadow-[var(--cp-shadow-1)]",
        // List variant: no border/shadow/rounded (used inside divide-y container)
        isListVariant && "rounded-none border-0 shadow-none",
        // Interactive styles (hover, focus) for both variants
        isInteractive &&
          !isListVariant &&
          "cursor-pointer hover:border-primary/30 hover:shadow-lg hover:-translate-y-0.5 focus-within:border-primary/40 focus-within:ring-2 focus-within:ring-primary/10",
        isInteractive && isListVariant && "cursor-pointer hover:bg-muted focus-within:bg-muted",
        className
      )}
      onClick={onClick}
      onKeyDown={handleKeyDown}
      role={isInteractive ? "button" : undefined}
      tabIndex={isInteractive ? 0 : undefined}
    >
      <div className="px-5 sm:px-6 py-5">
        <div className="flex items-start justify-between gap-4 sm:gap-6">
          {/* Left section: Icon + Service info + Status */}
          <div className="flex items-start gap-3 sm:gap-4 flex-1 min-w-0">
            <div
              className={cn(
                "flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-xl",
                iconStyles
              )}
            >
              {serviceIcon}
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 flex-wrap">
                <h3 className="font-semibold text-foreground">{serviceName}</h3>
                <StatusPill label={statusDescriptor.label} variant={statusVariant} />
              </div>
              <div className="mt-1.5 flex items-center gap-2 text-xs text-muted-foreground">
                <span className="font-medium">
                  #{order.orderNumber || String(order.id).slice(-8)}
                </span>
                <span className="text-muted-foreground/40">•</span>
                <span>{formattedCreatedDate || "—"}</span>
              </div>
              {displayItems.length > 0 && (
                <div className="mt-3 flex flex-wrap gap-2">
                  {displayItems.map(item => (
                    <span
                      key={item.id}
                      className="inline-flex items-center rounded-lg bg-muted px-2.5 py-1 text-xs font-medium text-muted-foreground"
                    >
                      {item.name}
                    </span>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Right section: Pricing */}
          {showPricing && (
            <div className="flex items-start gap-4 sm:gap-5 flex-shrink-0">
              {totals.monthlyTotal > 0 && (
                <div className="text-right">
                  <p className="text-[10px] font-semibold uppercase tracking-wider text-primary">
                    Monthly
                  </p>
                  <p className="text-xl font-bold text-foreground tabular-nums">
                    ¥{totals.monthlyTotal.toLocaleString()}
                  </p>
                </div>
              )}
              {totals.oneTimeTotal > 0 && (
                <div className="text-right">
                  <p className="text-[10px] font-semibold uppercase tracking-wider text-primary">
                    One-Time
                  </p>
                  <p className="text-lg font-bold text-foreground tabular-nums">
                    ¥{totals.oneTimeTotal.toLocaleString()}
                  </p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
      {footer && (
        <div
          className={cn(
            "border-t border-border bg-muted/30 px-5 sm:px-6 py-3",
            isListVariant && "border-t-0 bg-transparent"
          )}
        >
          {footer}
        </div>
      )}
    </article>
  );
}

export default OrderCard;
