"use client"

import { useQuery } from "convex/react"
import { useParams } from "next/navigation"
import { api } from "../../../../../../../convex/_generated/api"
import type { Id } from "../../../../../../../convex/_generated/dataModel"
import { Skeleton } from "@/components/ui/skeleton"
import { Card, CardContent, CardHeader } from "@/components/ui/card"
import { OrderPageHeader } from "@/components/orders/detail/OrderPageHeader"
import { OrderItemsCard } from "@/components/orders/detail/OrderItemsCard"
import { OrderFinancialsCard } from "@/components/orders/detail/OrderFinancialsCard"
import { CustomerCard } from "@/components/orders/detail/CustomerCard"
import { ShippingAddressCard } from "@/components/orders/detail/ShippingAddressCard"
import { FulfilmentCard } from "@/components/orders/detail/FulfilmentCard"
import { OrderTimelineCard } from "@/components/orders/detail/OrderTimelineCard"
import { OrderActionsBar } from "@/components/orders/detail/OrderActionsBar"

// ─── Per-card skeletons (no layout shift on load) ─────────────────────────────

function HeaderSkeleton() {
  return (
    <div className="flex flex-col gap-2">
      <Skeleton className="h-8 w-20" />
      <div className="flex items-center gap-2">
        <Skeleton className="h-7 w-32" />
        <Skeleton className="h-5 w-20 rounded-full" />
        <Skeleton className="h-5 w-16 rounded-full" />
        <Skeleton className="h-4 w-36" />
      </div>
    </div>
  )
}

function CardSkeleton({ rows = 3 }: { rows?: number }) {
  return (
    <Card>
      <CardHeader>
        <Skeleton className="h-5 w-28" />
      </CardHeader>
      <CardContent className="flex flex-col gap-3">
        {Array.from({ length: rows }).map((_, i) => (
          <Skeleton key={i} className="h-4 w-full" />
        ))}
      </CardContent>
    </Card>
  )
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function OrderDetailPage() {
  const params = useParams()
  const orderId = params.id as Id<"orders">

  const order = useQuery(api.orders.getById, { id: orderId })
  // Timeline query is wired here for Phase 5 — passed to OrderTimelineCard
  const events = useQuery(api.orders.getTimeline, { orderId })

  // ── Loading state ───────────────────────────────────────────────────────────
  if (order === undefined) {
    return (
      <main className="flex flex-1 flex-col gap-6 p-4 pt-0">
        <HeaderSkeleton />
        <div className="grid grid-cols-1 gap-6 md:grid-cols-[1fr_340px]">
          {/* Left column */}
          <div className="flex flex-col gap-6">
            <CardSkeleton rows={4} />
            <CardSkeleton rows={4} />
            <CardSkeleton rows={5} />
          </div>
          {/* Right column */}
          <div className="flex flex-col gap-6">
            <CardSkeleton rows={2} />
            <CardSkeleton rows={3} />
            <CardSkeleton rows={4} />
          </div>
        </div>
      </main>
    )
  }

  return (
    <main className="flex flex-1 flex-col gap-6 p-4 pt-0">
      {/* Header — back link, order#, date, status badges */}
      <OrderPageHeader
        orderNumber={order.orderNumber}
        createdAt={order.createdAt}
        status={order.status}
        paymentStatus={order.paymentStatus}
      />

      <OrderActionsBar
        orderId={order._id}
        status={order.status}
        paymentStatus={order.paymentStatus}
        trackingNumber={order.trackingNumber}
        returnRequestedAt={order.returnRequestedAt}
        returnReceivedAt={order.returnReceivedAt}
        total={order.total}
        currency={order.currency}
      />

      {/* Two-column layout */}
      <div className="grid grid-cols-1 gap-6 md:grid-cols-[1fr_340px]">
        {/* ── Left column ──────────────────────────────────────────────────── */}
        <div className="flex flex-col gap-6">
          <OrderItemsCard items={order.items} currency={order.currency} />
          <OrderFinancialsCard
            subtotal={order.subtotal}
            shipping={order.shipping}
            discount={order.discount}
            tax={order.tax}
            total={order.total}
            currency={order.currency}
          />
          <OrderTimelineCard events={events} />
        </div>

        {/* ── Right column ─────────────────────────────────────────────────── */}
        <div className="flex flex-col gap-6">
          <CustomerCard
            name={order.shippingAddressSnapshot.fullName}
            email={order.email}
          />
          <ShippingAddressCard address={order.shippingAddressSnapshot} />
          <FulfilmentCard
            carrier={order.carrier}
            shippingMethod={order.shippingMethod}
            shippingServiceCode={order.shippingServiceCode}
            trackingNumber={order.trackingNumber}
            trackingUrl={order.trackingUrl}
            labelUrl={order.labelUrl}
            returnLabelUrl={order.returnLabelUrl}
            trackingStatus={order.trackingStatus}
            estimatedDelivery={order.estimatedDelivery}
            actualDelivery={order.actualDelivery}
            status={order.status}
          />
        </div>
      </div>
    </main>
  )
}
