"use client";

import { ReactNode, useMemo, type KeyboardEvent } from "react";
import { StatusPill } from "@/components/atoms/status-pill";
import {
  WifiIcon,
  DevicePhoneMobileIcon,
  LockClosedIcon,
  CubeIcon,
} from "@heroicons/react/24/outline";
import {
  calculateOrderTotals,
  deriveOrderStatusDescriptor,
  getServiceCategory,
} from "@/features/orders/utils/order-presenters";
import { buildOrderDisplayItems } from "@/features/orders/utils/order-display";
import type { OrderSummary } from "@customer-portal/domain/orders";
import { cn } from "@/lib/utils/cn";

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

export interface OrderCardProps {
  order: OrderSummaryLike;
  onClick?: () => void;
  footer?: ReactNode;
  className?: string;
}

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

const SERVICE_ICON_STYLES = {
  internet: "bg-blue-50 text-blue-600",
  sim: "bg-violet-50 text-violet-600",
  vpn: "bg-teal-50 text-teal-600",
  default: "bg-slate-50 text-slate-600",
} as const;

const renderServiceIcon = (orderType?: string): ReactNode => {
  const category = getServiceCategory(orderType);
  switch (category) {
    case "internet":
      return <WifiIcon className="h-6 w-6" />;
    case "sim":
      return <DevicePhoneMobileIcon className="h-6 w-6" />;
    case "vpn":
      return <LockClosedIcon className="h-6 w-6" />;
    default:
      return <CubeIcon className="h-6 w-6" />;
  }
};

export function OrderCard({ order, onClick, footer, className }: 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 = renderServiceIcon(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?.();
    }
  };

  return (
    <article
      key={String(order.id)}
      className={cn(
        "group overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm transition-all focus-visible:outline-none",
        isInteractive &&
          "cursor-pointer hover:border-blue-200 hover:shadow-md focus-within:border-blue-300 focus-within:ring-2 focus-within:ring-blue-100",
        className
      )}
      onClick={onClick}
      onKeyDown={handleKeyDown}
      role={isInteractive ? "button" : undefined}
      tabIndex={isInteractive ? 0 : undefined}
    >
      <div className="px-6 py-4">
        <div className="flex items-start justify-between gap-6">
          {/* Left section: Icon + Service info + Status */}
          <div className="flex items-start gap-3 flex-1 min-w-0">
            <div
              className={cn(
                "flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg",
                iconStyles
              )}
            >
              {serviceIcon}
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 flex-wrap">
                <h3 className="font-semibold text-gray-900">{serviceName}</h3>
                <StatusPill label={statusDescriptor.label} variant={statusVariant} />
              </div>
              <div className="mt-1 flex items-center gap-2 text-xs text-gray-500">
                <span className="font-medium">
                  #{order.orderNumber || String(order.id).slice(-8)}
                </span>
                <span>•</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-md bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-700"
                    >
                      {item.name}
                    </span>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Right section: Pricing */}
          {showPricing && (
            <div className="flex items-start gap-4 flex-shrink-0">
              {totals.monthlyTotal > 0 && (
                <div className="text-right">
                  <p className="text-[10px] font-medium uppercase tracking-wider text-blue-600">
                    Monthly
                  </p>
                  <p className="text-xl font-bold text-gray-900">
                    ¥{totals.monthlyTotal.toLocaleString()}
                  </p>
                </div>
              )}
              {totals.oneTimeTotal > 0 && (
                <div className="text-right">
                  <p className="text-[10px] font-medium uppercase tracking-wider text-blue-600">
                    One-Time
                  </p>
                  <p className="text-lg font-bold text-gray-900">
                    ¥{totals.oneTimeTotal.toLocaleString()}
                  </p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
      {footer && <div className="border-t border-slate-100 bg-slate-50 px-6 py-3">{footer}</div>}
    </article>
  );
}

export default OrderCard;
