"use client";

import {
  X,
  ShoppingCart,
  Package,
  CreditCard,
  Building2,
  Clock,
  Truck,
  CheckCircle,
  Hash,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { BusinessCardPreview } from "@/features/delivery-management/components/business-card-preview";
import type {
  OrderResponseDTO,
  OrderStatus,
  OrderItemResponseDTO,
  BusinessCardResponseDTO,
} from "../dtos/order.dto";

// ============================================
// Status Badge
// ============================================
function StatusBadge({ status }: { status: OrderStatus }) {
  const config: Record<
    OrderStatus,
    { styles: string; icon: React.ReactNode; label: string }
  > = {
    ordered: {
      styles: "bg-amber-50 text-amber-700 border-amber-200",
      icon: <Clock className="h-3.5 w-3.5" />,
      label: "Ordered",
    },
    processing: {
      styles: "bg-blue-50 text-blue-700 border-blue-200",
      icon: <Package className="h-3.5 w-3.5" />,
      label: "Processing",
    },
    dispatched: {
      styles: "bg-purple-50 text-purple-700 border-purple-200",
      icon: <Truck className="h-3.5 w-3.5" />,
      label: "Dispatched",
    },
    delivered: {
      styles: "bg-emerald-50 text-emerald-700 border-emerald-200",
      icon: <CheckCircle className="h-3.5 w-3.5" />,
      label: "Delivered",
    },
  };

  const { styles, icon, label } = config[status];

  return (
    <span
      className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium ${styles}`}
    >
      {icon}
      {label}
    </span>
  );
}

// ============================================
// Order Item Card
// ============================================
function OrderItemCard({ item }: { item: OrderItemResponseDTO }) {
  // Map BusinessCardResponseDTO to DeliveryBusinessCardDTO for preview
  const mapCard = (card: BusinessCardResponseDTO) => ({
    id: card.id,
    deliveryOrderItemId: card.orderItemId,
    cardNumber: card.cardNumber,
    name: card.name,
    title: card.title,
    email: card.email,
    company: card.company,
    address: card.address,
    website: card.website,
    quantity: card.quantity,
    createdAt: card.createdAt,
    updatedAt: card.updatedAt,
  });
  return (
    <div className="rounded-xl border border-gray-200 bg-white p-4">
      <div className="mb-3 flex items-start justify-between">
        <div className="flex items-center gap-2">
          {item.imageUrl ? (
            <img
              src={item.imageUrl}
              alt={item.productName}
              className="h-8 w-8 rounded-lg object-cover"
            />
          ) : (
            <div
              className={`flex h-8 w-8 items-center justify-center rounded-lg ${
                item.isBusinessCard ? "bg-pink-50" : "bg-purple-50"
              }`}
            >
              {item.isBusinessCard ? (
                <CreditCard className="h-4 w-4 text-pink-600" />
              ) : (
                <Package className="h-4 w-4 text-purple-600" />
              )}
            </div>
          )}
          <div>
            <p className="text-sm font-semibold text-gray-900">
              {item.productName}
            </p>
            <div className="flex items-center gap-1.5 text-xs text-gray-500">
              {item.variantName && <span>· {item.variantName}</span>}
              {item.size && <span>· {item.size}</span>}
            </div>
          </div>
        </div>
        <div className="text-right">
          <p className="text-sm font-bold text-gray-900">
            ×{item.quantity.toLocaleString()}
          </p>
          {item.unitPrice !== null && (
            <p className="text-xs text-gray-500">
              ${item.unitPrice.toFixed(2)} ea
            </p>
          )}
        </div>
      </div>

      {/* Business Cards */}
      {item.isBusinessCard && item.businessCards.length > 0 && (
        <div className="mt-3 border-t border-gray-100 pt-3">
          <div className="mb-3 flex items-center justify-between">
            <p className="text-xs font-medium text-gray-500 uppercase tracking-wider">
              Business Cards ({item.businessCards.length})
            </p>
            <span className="text-xs font-semibold text-[#1a6b5a]">
              Total: {item.businessCards.reduce((sum, bc) => sum + (bc.quantity || 0), 0).toLocaleString()} cards
            </span>
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            {item.businessCards.map((card) => (
              <div key={card.id} className="rounded-lg border border-gray-200 bg-gray-50 p-3">
                <div className="mb-2 flex items-center justify-between">
                  <span className="text-xs font-semibold text-gray-700">
                    Card #{card.cardNumber} — {card.name}
                  </span>
                  <span className="rounded-full bg-[#1a6b5a]/10 px-2 py-0.5 text-[10px] font-bold text-[#1a6b5a]">
                    ×{card.quantity?.toLocaleString() ?? 0}
                  </span>
                </div>
                <BusinessCardPreview card={mapCard(card)} format="both" />
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ============================================
// Order Detail Props
// ============================================
interface OrderDetailProps {
  isOpen: boolean;
  onClose: () => void;
  order: OrderResponseDTO | null;
}

// ============================================
// Order Detail Component (White Theme)
// ============================================
export function OrderDetail({
  isOpen,
  onClose,
  order,
}: OrderDetailProps) {
  if (!isOpen || !order) return null;

  const totalQuantity = order.items.reduce(
    (sum, item) => sum + item.quantity,
    0
  );

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative z-10 mx-4 flex max-h-[90vh] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-50">
              <ShoppingCart className="h-5 w-5 text-indigo-600" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-lg font-semibold text-gray-900">
                  {order.orderNumber}
                </h2>
                <StatusBadge status={order.status} />
              </div>
              <p className="text-xs text-gray-500">
                {new Date(order.createdAt).toLocaleDateString("en-US", {
                  weekday: "long",
                  year: "numeric",
                  month: "long",
                  day: "numeric",
                })}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Content — scrollable */}
        <div className="flex-1 overflow-y-auto p-6">
          <div className="space-y-6">
            {/* Order Info */}
            <div className="rounded-xl border border-gray-200 bg-gray-50 p-4">
              <div className="grid gap-4 sm:grid-cols-4">
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Company
                  </p>
                  <div className="mt-1 flex items-center gap-2">
                    <Building2 className="h-4 w-4 text-gray-400" />
                    <p className="text-sm font-medium text-gray-900">
                      {order.companyName}
                    </p>
                  </div>
                </div>
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Department
                  </p>
                  <div className="mt-1 flex items-center gap-2">
                    <Building2 className="h-4 w-4 text-indigo-400" />
                    <p className="text-sm font-medium text-gray-900">
                      {order.departmentName}
                    </p>
                  </div>
                </div>
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Total Items
                  </p>
                  <p className="mt-1 text-sm font-medium text-gray-900">
                    {order.items.length} product
                    {order.items.length !== 1 ? "s" : ""}
                  </p>
                </div>
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Total Quantity
                  </p>
                  <p className="mt-1 text-sm font-medium text-gray-900">
                    {totalQuantity.toLocaleString()} units
                  </p>
                </div>
              </div>
              {order.notes && (
                <div className="mt-3 border-t border-gray-200 pt-3">
                  <p className="text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Notes
                  </p>
                  <p className="mt-1 text-sm text-gray-700">{order.notes}</p>
                </div>
              )}
            </div>

            {/* Order Items */}
            <div>
              <h3 className="mb-3 text-sm font-semibold text-gray-900">
                Order Items
              </h3>
              <div className="space-y-3">
                {order.items.map((item) => (
                  <OrderItemCard key={item.id} item={item} />
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end border-t border-gray-200 px-6 py-4">
          <Button type="button" variant="ghost" onClick={onClose}>
            Close
          </Button>
        </div>
      </div>
    </div>
  );
}
