import { Card } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Separator } from "@/components/ui/separator"
import { FREE_SHIPPING_THRESHOLD_CENTS } from "@/lib/pricing"

interface OrderItem {
  name: string
  quantity: number
  price: number
  image?: string
}

interface OrderData {
  id?: number
  items: OrderItem[]
  subtotal: number
  shipping: number
  originalShipping?: number  // Original shipping before free shipping discount
  tax: number
  total: number
  currency?: string
}

interface OrderSummaryProps {
  orderData?: OrderData
  isLoading: boolean
  error?: string | null
}

export function OrderSummary({ orderData, isLoading, error }: OrderSummaryProps) {
  if (isLoading) {
    return <OrderSummarySkeleton />
  }

  if (error) {
    return (
      <Card className="p-10 shadow-elevated border-border/50 bg-card/80 backdrop-blur-sm">
        <div className="text-center">
          <div className="inline-flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10 mb-4">
            <svg
              className="h-6 w-6 text-destructive"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-foreground mb-2">Unable to Load Order</h3>
          <p className="text-sm text-muted-foreground">{error}</p>
        </div>
      </Card>
    )
  }

  if (!orderData) {
    return null
  }

  const data = orderData

  return (
    <Card className="p-10 shadow-elevated border-border/50 bg-card/80 backdrop-blur-sm">
      <div className="mb-8">
        <h2 className="text-3xl font-bold text-foreground tracking-tight">Order Details</h2>
        <p className="mt-2 text-sm text-muted-foreground">Review your purchase</p>
      </div>

      <div className="space-y-6">
        {data.items.map((item, index) => (
          <div key={`${item.name}-${index}`} className="flex items-start justify-between gap-6">
            <div className="flex-1 min-w-0">
              <p className="text-base font-medium text-foreground leading-relaxed">{item.name}</p>
              <p className="mt-2 text-sm text-muted-foreground tabular-nums">Quantity {item.quantity}</p>
            </div>
            <p className="text-base font-semibold text-foreground whitespace-nowrap tabular-nums">
              ${(item.price / 100).toFixed(2)}
            </p>
          </div>
        ))}
      </div>

      <Separator className="my-8" />

      <div className="space-y-4">
        <PriceRow label="Subtotal" amount={data.subtotal} />
        <PriceRow
          label="Shipping"
          amount={data.shipping}
          originalAmount={data.shipping === 0 && data.originalShipping ? data.originalShipping : undefined}
          free={data.shipping === 0}
          discountReason={data.shipping === 0 && data.subtotal >= FREE_SHIPPING_THRESHOLD_CENTS ? "Free shipping on orders over $200" : undefined}
        />
        <PriceRow label="Sales Tax" amount={data.tax} />
      </div>

      <Separator className="my-8" />

      <div className="flex items-baseline justify-between">
        <span className="text-lg font-medium text-muted-foreground">Total</span>
        <div className="text-right">
          <span className="text-4xl font-bold text-foreground tabular-nums tracking-tight">
            ${(data.total / 100).toFixed(2)}
          </span>
          <p className="mt-1 text-xs text-muted-foreground">{data.currency || 'USD'}</p>
        </div>
      </div>
    </Card>
  )
}

function PriceRow({
  label,
  amount,
  originalAmount,
  free = false,
  discountReason,
}: {
  label: string
  amount: number
  originalAmount?: number
  free?: boolean
  discountReason?: string
}) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-base text-muted-foreground">{label}</span>
      <div className="text-right">
        <span className="text-base font-medium text-foreground tabular-nums">
          {free ? (
            <span className="flex items-center justify-end gap-2">
              {originalAmount && originalAmount > 0 && (
                <span className="text-muted-foreground line-through">
                  ${(originalAmount / 100).toFixed(2)}
                </span>
              )}
              <span className="text-green-600 dark:text-green-400 font-semibold">Free</span>
            </span>
          ) : (
            `$${(amount / 100).toFixed(2)}`
          )}
        </span>
        {discountReason && (
          <p className="text-xs text-green-600 dark:text-green-400 mt-0.5">{discountReason}</p>
        )}
      </div>
    </div>
  )
}

function OrderSummarySkeleton() {
  return (
    <Card className="p-10 shadow-elevated border-border/50 bg-card/80 backdrop-blur-sm">
      <div className="mb-8">
        <Skeleton className="h-9 w-48 mb-2" />
        <Skeleton className="h-4 w-32" />
      </div>

      <div className="space-y-4">
        {[1, 2].map((i) => (
          <div key={i} className="flex items-start justify-between gap-4">
            <div className="flex-1 space-y-2">
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-3 w-12" />
            </div>
            <Skeleton className="h-4 w-16" />
          </div>
        ))}
      </div>

      <Separator className="my-8" />

      <div className="space-y-3">
        {[1, 2, 3].map((i) => (
          <div key={i} className="flex items-center justify-between">
            <Skeleton className="h-4 w-20" />
            <Skeleton className="h-4 w-16" />
          </div>
        ))}
      </div>

      <Separator className="my-8" />

      <div className="flex items-baseline justify-between">
        <Skeleton className="h-6 w-16" />
        <div className="text-right space-y-2">
          <Skeleton className="h-10 w-32" />
          <Skeleton className="h-3 w-12 ml-auto" />
        </div>
      </div>
    </Card>
  )
}
