"use client";

import { useRef } from "react";

import { toast } from "sonner";
import { useShallow } from "zustand/react/shallow";

import type { Role } from "@/lib/auth";
import { nextStagesForRole } from "@/lib/order/state-machine";
import { useOrdersStore } from "@/stores/orders/orders-store";
import type { Order, OrderStage } from "@/lib/order/types";

import { AddressSection } from "./address-section";
import { CustomerSection } from "./customer-section";
import { ItemsSection } from "./items-section";
import { MessagesSection } from "./messages-section";
import { QuickActions } from "./quick-actions";
import { TicketActionBar } from "./ticket-action-bar";
import { TicketStageStrip } from "./ticket-stage-strip";
import { TimelineSection } from "./timeline-section";
import { TotalsSection } from "./totals-section";

interface OrderTicketProps {
  order: Order;
  role: Role;
  readOnly?: boolean;
  onNew?: () => void;
  onNavigate?: (direction: "prev" | "next" | "prevHour" | "nextHour" | "prevDay" | "nextDay") => void;
  /** Called after cancel so parent can close the sheet */
  onClose?: () => void;
}

export function OrderTicket({
  order,
  role,
  readOnly = false,
  onNew,
  onNavigate,
  onClose,
}: OrderTicketProps) {
  const timelineRef = useRef<HTMLDivElement>(null);
  const quickActionsRef = useRef<HTMLDivElement>(null);
  const { transition, assignDriver, drivers, duplicateOrder, cancelOrder, markOrderPaid, addMenuGivenDate, updateCustomerMessage, updateAddress, updateItems, orders } = useOrdersStore(
    useShallow((s) => ({
      transition: s.transition,
      assignDriver: s.assignDriver,
      drivers: s.drivers,
      duplicateOrder: s.duplicateOrder,
      cancelOrder: s.cancelOrder,
      markOrderPaid: s.markOrderPaid,
      addMenuGivenDate: s.addMenuGivenDate,
      updateCustomerMessage: s.updateCustomerMessage,
      updateAddress: s.updateAddress,
      updateItems: s.updateItems,
      orders: s.orders,
    })),
  );

  // Only admin and foh can create/edit orders; all other roles are view-only for edit actions
  const canEdit = !readOnly && (role === "admin" || role === "foh");
  const hasAllowedTransitions = !readOnly && nextStagesForRole(order, role).some((r) => r.result.ok);

  const handleTransition = (target: OrderStage) => {
    transition(order.id, target);
  };

  const handleAssignDriver = (driverId: string) => {
    assignDriver(order.id, driverId);
  };

  const handleScrollToTimeline = () => {
    timelineRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  const handlePrint = () => {
    window.print();
  };

  // Find the most recent completed/out_for_delivery order for the same customer (by mobile)
  const lastOrderForCustomer = orders
    .filter(
      (o) =>
        o.id !== order.id &&
        o.customer.mo === order.customer.mo &&
        (o.stage === "completed" || o.stage === "out_for_delivery"),
    )
    .sort((a, b) => new Date(b.orderedAt).getTime() - new Date(a.orderedAt).getTime())[0];

  const handleViewLastOrderFull = lastOrderForCustomer
    ? () => { window.location.href = `/orders/${lastOrderForCustomer.id}`; }
    : undefined;

  return (
    <div className="flex h-full flex-col overflow-hidden rounded-none bg-background">
      {/* Fixed top: action bar + stage strip */}
      <div className="shrink-0">
        <TicketActionBar
          orderId={order.id}
          role={role}
          canChangeStatus={hasAllowedTransitions}
          readOnly={readOnly}
          onNew={onNew}
          onPrint={handlePrint}
          onScrollToTimeline={handleScrollToTimeline}
          onOpenStatusSheet={() => quickActionsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" })}
          onPrev={() => onNavigate?.("prev")}
          onNext={() => onNavigate?.("next")}
          onPrevHour={() => onNavigate?.("prevHour")}
          onNextHour={() => onNavigate?.("nextHour")}
          onPrevDay={() => onNavigate?.("prevDay")}
          onNextDay={() => onNavigate?.("nextDay")}
        />
        <TicketStageStrip order={order} />
      </div>

      {/* Scrollable body */}
      <div className="flex-1 overflow-y-auto">
        {order.type === "delivery" && order.address && (
          <AddressSection
            address={order.address}
            onAddressSelect={canEdit ? (addr) => updateAddress(order.id, addr) : undefined}
          />
        )}

        <CustomerSection
          customer={order.customer}
          menuGivenDates={order.menuGivenDates}
          onMarkMenuToday={canEdit ? () => addMenuGivenDate(order.id) : undefined}
          onViewLastOrder={handleViewLastOrderFull}
        />

        <ItemsSection
          order={order}
          readOnly={!canEdit}
          onAddItem={canEdit ? (item) => updateItems(order.id, [...order.items, item]) : undefined}
          onUpdateItem={canEdit ? (items) => updateItems(order.id, items) : undefined}
        />

        <TotalsSection
          charges={order.charges}
          orderId={order.id}
          customerMo={order.customer.mo}
          customerNa={order.customer.na}
          stage={order.stage}
          readOnly={!canEdit}
          onSave={canEdit ? () => toast.success("Order saved") : undefined}
          onRepeat={canEdit ? () => {
            const newOrder = duplicateOrder(order.id);
            if (newOrder) toast.success(`Repeated as ${newOrder.id}`);
          } : undefined}
          onCancel={canEdit ? () => {
            cancelOrder(order.id);
            toast.success(`Order ${order.id} cancelled`);
            onClose?.();
          } : undefined}
          onMarkPaid={canEdit ? () => {
            markOrderPaid(order.id);
            toast.success(`Order ${order.id} marked as paid`);
          } : undefined}
        />

        <MessagesSection
          message={order.customerMessage}
          readOnly={!canEdit}
          onUpdate={canEdit ? (msg) => updateCustomerMessage(order.id, msg) : undefined}
        />

        <div ref={timelineRef}>
          <TimelineSection events={order.events} />
        </div>
      </div>

      {/* Quick actions pinned at bottom */}
      {!readOnly && (
        <div ref={quickActionsRef} className="shrink-0 border-t bg-card">
          <QuickActions
            order={order}
            role={role}
            drivers={drivers}
            onTransition={handleTransition}
            onAssignDriver={handleAssignDriver}
          />
        </div>
      )}
    </div>
  );
}
