"use client";

import { useState } from "react";
import { useQuery } from "convex/react";
import { Breadcrumbs, toast } from "@heroui/react";
import Link from "next/link";
import { api } from "../../../../../convex/_generated/api";
import type { Id } from "../../../../../convex/_generated/dataModel";
import { ORDERS_PATH, useOrderDetail, useOrderActions } from "@/lib/orders";
import { useCartSession } from "@/lib/session";
import { OrderHeader } from "./detail/OrderHeader";
import { OrderLineItems } from "./detail/OrderLineItems";
import { OrderPriceSummary } from "./detail/OrderPriceSummary";
import { OrderAddresses } from "./detail/OrderAddresses";
import { OrderTrackingInfo } from "./detail/OrderTrackingInfo";
import { OrderActions } from "./detail/OrderActions";
import { OrderTimeline } from "./detail/OrderTimeline";
import { CancelOrderDialog } from "./actions/CancelOrderDialog";
import { ReorderConfirmDialog } from "./actions/ReorderConfirmDialog";
import { RequestReturnDialog } from "./actions/RequestReturnDialog";
import { OrderDetailSkeleton } from "./state/OrderDetailSkeleton";

interface Props {
  orderId: string;
}

export function OrderDetailPageView({ orderId }: Props) {
  const { order, isLoading } = useOrderDetail(orderId);
  const timelineEvents = useQuery(
    api.orders.getTimeline,
    order ? { orderId: orderId as Id<"orders"> } : "skip",
  ) ?? [];
  const { cancelOrder, isCancelling, requestReturn, isRequestingReturn, reorderItems, isReordering } =
    useOrderActions();
  const { sessionId } = useCartSession();

  const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
  const [returnDialogOpen, setReturnDialogOpen] = useState(false);
  const [reorderDialogOpen, setReorderDialogOpen] = useState(false);

  if (isLoading) return <OrderDetailSkeleton />;

  if (!order) {
    return (
      <div className="py-16 text-center">
        <p className="text-gray-500">Order not found.</p>
        <Link
          href={ORDERS_PATH}
          className="mt-4 inline-block text-sm font-medium text-[#38a99f] hover:text-[#236f6b]"
        >
          ← Back to Orders
        </Link>
      </div>
    );
  }

  const handleConfirmCancel = async () => {
    const result = await cancelOrder(orderId);
    setCancelDialogOpen(false);
    if (result.success) {
      toast.success("Order cancelled successfully.");
    } else {
      toast.danger("Failed to cancel order. Please try again.");
    }
  };

  const handleConfirmReturn = async () => {
    const result = await requestReturn(orderId);
    setReturnDialogOpen(false);
    if (result.success) {
      toast.success("Return requested. We'll be in touch with next steps.");
    } else {
      toast.danger("Failed to submit return request. Please try again.");
    }
  };

  const handleConfirmReorder = async () => {
    const { added, skipped } = await reorderItems(order.items, sessionId);
    setReorderDialogOpen(false);
    const total = order.items.length;
    if (skipped === 0) {
      toast.success(
        `All ${added} ${added === 1 ? "item" : "items"} added to your cart.`,
      );
    } else if (added === 0) {
      toast.danger(
        "No items could be added — they are no longer available.",
      );
    } else {
      toast(`${added} of ${total} items added to cart.`, {
        description: `${skipped} ${skipped === 1 ? "item was" : "items were"} no longer available.`,
      });
    }
  };

  return (
    <div className="space-y-6">
      {/* Breadcrumbs */}
      <Breadcrumbs>
        <Breadcrumbs.Item href="/account">Account</Breadcrumbs.Item>
        <Breadcrumbs.Item href={ORDERS_PATH}>Orders</Breadcrumbs.Item>
        <Breadcrumbs.Item>Order {order.orderNumber}</Breadcrumbs.Item>
      </Breadcrumbs>

      {/* Header */}
      <OrderHeader
        orderNumber={order.orderNumber}
        status={order.status}
        paymentStatus={order.paymentStatus}
        createdAt={order.createdAt}
        paidAt={order.paidAt}
      />

      {/* Main grid — items/tracking/addresses left, summary right */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        <div className="space-y-6 lg:col-span-2">
          <OrderLineItems items={order.items} currency={order.currency} />
          <OrderTrackingInfo
            carrier={order.carrier}
            shippingMethod={order.shippingMethod}
            trackingNumber={order.trackingNumber}
            trackingUrl={order.trackingUrl}
            estimatedDelivery={order.estimatedDelivery}
            shippedAt={order.shippedAt}
            actualDelivery={order.actualDelivery}
            status={order.status}
          />
          <OrderAddresses
            shippingAddress={order.shippingAddressSnapshot}
            billingAddress={order.billingAddressSnapshot}
          />
        </div>

        <div>
          <OrderPriceSummary
            subtotal={order.subtotal}
            shipping={order.shipping}
            tax={order.tax}
            discount={order.discount}
            total={order.total}
            currency={order.currency}
          />
        </div>
      </div>

      {/* Actions */}
      <OrderActions
        order={order}
        onCancel={() => setCancelDialogOpen(true)}
        isCancelling={isCancelling}
        onRequestReturn={() => setReturnDialogOpen(true)}
        isRequestingReturn={isRequestingReturn}
        onReorder={() => setReorderDialogOpen(true)}
        isReordering={isReordering}
      />

      {/* Timeline */}
      <OrderTimeline events={timelineEvents} />

      {/* Dialogs */}
      <RequestReturnDialog
        isOpen={returnDialogOpen}
        onClose={() => setReturnDialogOpen(false)}
        onConfirm={handleConfirmReturn}
        isRequesting={isRequestingReturn}
        orderNumber={order.orderNumber}
      />
      <CancelOrderDialog
        isOpen={cancelDialogOpen}
        onClose={() => setCancelDialogOpen(false)}
        onConfirm={handleConfirmCancel}
        isCancelling={isCancelling}
        orderNumber={order.orderNumber}
      />
      <ReorderConfirmDialog
        isOpen={reorderDialogOpen}
        onClose={() => setReorderDialogOpen(false)}
        onConfirm={handleConfirmReorder}
        isReordering={isReordering}
        itemCount={order.items.length}
      />
    </div>
  );
}
