"use client";

import { formatQty, productLabel, quantityWithUnit, unitSummary } from "@/lib/product-unit";

import { OrderStatusBadge as StatusBadge } from "@/components/order-status-badge";

import { displayValue, formatDate } from "@/lib/display-format";

import {
  X,
  ShoppingCart,
  Package,
  CreditCard,
  Building2,
  Hash,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { BusinessCardPreview } from "@/features/delivery-management/components/business-card-preview";
import type {
  OrderResponseDTO,
  OrderItemResponseDTO,
  BusinessCardResponseDTO,
} from "../dtos/order.dto";

// ============================================
// 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">
              {productLabel(item.productName, item.defaultUnit)}
              {item.costPerPiece != null && <span className="ml-2 text-xs font-normal text-gray-500">Cost per piece (Rs): {item.costPerPiece.toFixed(2)}</span>}
            </p>
            <div className="flex items-center gap-1.5 text-xs text-gray-500">
              {item.variantName && <span>· {displayValue(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">
            ×{quantityWithUnit(item.quantity, item.defaultUnit)}
          </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: {formatQty(item.businessCards.reduce((sum, bc) => sum + (bc.quantity || 0), 0))}
            </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} — {displayValue(card.name)}
                  </span>
                  <span className="rounded-full bg-[#1a6b5a]/10 px-2 py-0.5 text-[10px] font-bold text-[#1a6b5a]">
                    ×{formatQty(card.quantity ?? 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">
                  {displayValue(order.orderNumber)}
                </h2>
                <StatusBadge status={order.status} />
              </div>
              <p className="text-xs text-gray-500">
                {formatDate(order.createdAt)}
              </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">
                      {displayValue(order.companyName)}
                    </p>
                  </div>
                </div>
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Community
                  </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">
                      {displayValue(order.departmentName)}
                    </p>
                  </div>
                </div>
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase tracking-wider">Community ZIP Code</p>
                  <p className="mt-1 text-sm text-gray-900">{displayValue(order.departmentZipCode)}</p>
                </div>
                <div>
                  <p className="text-xs font-medium text-gray-500 uppercase tracking-wider">Community Phone Number</p>
                  <p className="mt-1 text-sm text-gray-900">{displayValue(order.departmentPhone)}</p>
                </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()} {unitSummary(order.items)}
                  </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>
  );
}
