"use client";

import { Phone, Truck } from "lucide-react";
import type { ChatOrderTracking, OrderDetailBlock } from "@/lib/chat/types";
import { formatCurrency, formatDateShort, formatDateTime } from "@/lib/utils";
import { useChatBlocks } from "../ChatBlockContext";
import { BlockCard, ChatLink, OrderStageChip, Row } from "./shared";
import StatusStepper from "./StatusStepper";

function money(value: number | null | undefined): string | null {
  return typeof value === "number" && Number.isFinite(value) ? formatCurrency(value) : null;
}

function TrackingRow({ row }: { row: ChatOrderTracking }) {
  const { copy } = useChatBlocks();
  const phone = row.driver_phone ? row.driver_phone.replace(/[^\d+]/g, "") : "";

  return (
    <li className="rounded-lg bg-gray-50 p-2">
      <dl className="space-y-0.5">
        {row.vehicle_number ? <Row label={copy.vehicle}>{row.vehicle_number}</Row> : null}
        {row.driver_name || phone ? (
          <Row label={copy.driver}>
            <span className="inline-flex items-center gap-1.5">
              {row.driver_name}
              {phone ? (
                <a
                  href={`tel:${phone}`}
                  aria-label={copy.callDriver(row.driver_name || row.driver_phone || "")}
                  className="inline-flex items-center gap-0.5 rounded-md bg-white px-1.5 py-0.5 font-semibold text-[#CC1414] ring-1 ring-red-100 hover:bg-red-50"
                >
                  <Phone size={11} aria-hidden /> {row.driver_phone}
                </a>
              ) : null}
            </span>
          </Row>
        ) : null}
        {row.transporter_name ? <Row label={copy.transporter}>{row.transporter_name}</Row> : null}
        {row.tracking_number ? <Row label={copy.trackingNumber}>{row.tracking_number}</Row> : null}
      </dl>
      {row.status ? <p className="mt-0.5 text-right text-[10px] font-medium text-gray-500">{row.status}</p> : null}
    </li>
  );
}

export default function OrderDetail({ block }: { block: OrderDetailBlock }) {
  const { copy } = useChatBlocks();
  const order = block.order;
  if (!order) return null;

  const ref = order.order_id || order.rfq_ref || `#${order.id}`;
  const tracking = (Array.isArray(order.tracking) ? order.tracking : []).filter(
    (t) => t && (t.vehicle_number || t.driver_name || t.driver_phone || t.tracking_number || t.transporter_name)
  );
  const timeline = Array.isArray(order.timeline) ? order.timeline.filter((t) => t && t.label) : [];
  const amounts: { label: string; value: string | null; alert?: boolean }[] = [
    { label: copy.total, value: money(order.total_amount) },
    {
      label: copy.finalAmount,
      // 0 means "not finalised yet" on older orders, not a ₹0 bill.
      value: (order.final_amount ?? 0) > 0 && order.final_amount !== order.total_amount ? money(order.final_amount) : null,
    },
    { label: copy.paid, value: money(order.paid_amount) },
    { label: copy.due, value: money(order.due_amount), alert: (order.due_amount ?? 0) > 0 },
  ];

  return (
    <BlockCard className="space-y-3">
      <div className="flex items-start justify-between gap-2">
        <div className="min-w-0">
          <p className="truncate text-sm font-semibold text-gray-900">{order.product?.name || ref}</p>
          <p className="truncate text-[11px] text-gray-500">
            {ref}
            {order.brand ? ` · ${order.brand}` : ""}
            {order.created_at ? ` · ${formatDateShort(order.created_at)}` : ""}
          </p>
        </div>
        <OrderStageChip stage={order.stage} label={order.status_label} />
      </div>

      <StatusStepper stage={order.stage} />

      {order.stage === "cancelled" && order.cancel_reason ? (
        <p className="rounded-lg bg-red-50 px-2.5 py-1.5 text-red-800">
          <span className="font-semibold">{copy.cancelReason}:</span> {order.cancel_reason}
        </p>
      ) : null}

      <dl className="space-y-1 border-t border-gray-100 pt-2">
        {amounts.map(({ label, value, alert }) =>
          value ? (
            <Row key={label} label={label}>
              <span className={alert ? "text-[#CC1414]" : undefined}>{value}</span>
            </Row>
          ) : null
        )}
        {order.origin_city ? <Row label={copy.origin}>{order.origin_city}</Row> : null}
      </dl>

      {tracking.length > 0 ? (
        <section aria-label={copy.tracking}>
          <p className="mb-1 flex items-center gap-1 font-semibold text-gray-900">
            <Truck size={13} className="text-[#CC1414]" aria-hidden /> {copy.tracking}
          </p>
          <ul className="space-y-1.5">
            {tracking.map((row, i) => (
              <TrackingRow key={`${row.vehicle_number ?? "v"}-${i}`} row={row} />
            ))}
          </ul>
        </section>
      ) : null}

      {timeline.length > 0 ? (
        <section aria-label={copy.timeline}>
          <p className="mb-1 font-semibold text-gray-900">{copy.timeline}</p>
          <ol className="space-y-1 border-l-2 border-red-100 pl-3">
            {timeline.map((item, i) => (
              <li key={`${item.label}-${i}`} className="relative">
                <span aria-hidden className="absolute -left-[17px] top-1 h-2 w-2 rounded-full bg-[#CC1414]" />
                <p className="text-gray-800">{item.label}</p>
                {item.at ? <p className="text-[10px] text-gray-400">{formatDateTime(item.at)}</p> : null}
              </li>
            ))}
          </ol>
        </section>
      ) : null}

      <div className="flex flex-wrap items-center gap-3 border-t border-gray-100 pt-2 text-[11px]">
        <ChatLink href={order.href} arrow>
          {copy.viewDetails}
        </ChatLink>
        <ChatLink href={order.ledger_href} arrow>
          {copy.viewLedger}
        </ChatLink>
      </div>
    </BlockCard>
  );
}
