"use client";

import { useEffect, useState } from "react";
import { Timer } from "lucide-react";
import type { EnquiryDetailBlock } from "@/lib/chat/types";
import { formatCountdown } from "@/lib/chat/i18n";
import { formatCurrency, formatDateShort } from "@/lib/utils";
import { useChatBlocks } from "../ChatBlockContext";
import { BlockCard, ChatLink, EnquiryStageChip, Row, formatQuantity, secondaryButtonClass } from "./shared";

function secondsUntil(target: number): number {
  return Math.max(0, Math.ceil((target - Date.now()) / 1000));
}

/** Ticks once a second until `target` (epoch ms); the interval is torn down on unmount. */
function useSecondsLeft(target: number): number {
  const [left, setLeft] = useState(() => secondsUntil(target));

  useEffect(() => {
    const tick = () => {
      const next = secondsUntil(target);
      setLeft(next);
      return next > 0;
    };
    if (!tick()) return;
    const timer = window.setInterval(() => {
      if (!tick()) window.clearInterval(timer);
    }, 1000);
    return () => window.clearInterval(timer);
  }, [target]);

  return left;
}

function LiveCountdown({ target, onRefresh }: { target: number; onRefresh: () => void }) {
  const { copy, busy } = useChatBlocks();
  const left = useSecondsLeft(target);

  if (left <= 0) {
    return (
      <div className="flex items-center justify-between gap-2 rounded-lg bg-gray-50 px-2.5 py-2">
        <span className="text-gray-600">{copy.biddingEnded}</span>
        <button type="button" onClick={onRefresh} disabled={busy} className={secondaryButtonClass}>
          {copy.refreshStatus}
        </button>
      </div>
    );
  }

  return (
    <div className="flex items-center justify-between gap-2 rounded-lg bg-amber-50 px-2.5 py-2 text-amber-800 ring-1 ring-amber-100">
      <span className="inline-flex items-center gap-1.5 font-semibold">
        <span className="relative flex h-2 w-2" aria-hidden>
          <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-75" />
          <span className="relative inline-flex h-2 w-2 rounded-full bg-amber-500" />
        </span>
        {copy.biddingLive}
      </span>
      {/* Opted out of the log's live region: announcing every tick would flood screen readers. */}
      <span className="inline-flex items-center gap-1 font-mono text-[11px] tabular-nums" aria-live="off">
        <Timer size={12} aria-hidden /> {copy.endsIn(formatCountdown(left))}
      </span>
    </div>
  );
}

export default function EnquiryDetail({ block, receivedAt }: { block: EnquiryDetailBlock; receivedAt: number }) {
  const { copy, sendAction } = useChatBlocks();
  const enquiry = block.enquiry;
  if (!enquiry) return null;

  const ref = enquiry.ref || `#${enquiry.id}`;
  const qty = formatQuantity(enquiry.quantity, enquiry.unit_label);
  const bidding = enquiry.bidding;
  // seconds_left is relative to when this reply arrived, which makes it immune
  // to client/server clock skew (ends_at is not).
  const target = receivedAt + Math.max(0, Number(bidding?.seconds_left) || 0) * 1000;

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

      {bidding?.is_live ? (
        <LiveCountdown
          target={target}
          onRefresh={() => void sendAction({ type: "enquiry.status", payload: { id: enquiry.id } })}
        />
      ) : null}

      <dl className="space-y-1">
        {qty ? <Row label={copy.quantity}>{qty}</Row> : null}
        {enquiry.delivery_city ? <Row label={copy.deliveryCity}>{enquiry.delivery_city}</Row> : null}
        {enquiry.required_by ? <Row label={copy.requiredBy}>{enquiry.required_by}</Row> : null}
        {bidding && typeof bidding.best_for_price === "number" ? (
          <Row label={copy.bestPrice}>
            <span className="text-emerald-700">{formatCurrency(bidding.best_for_price)}</span>
            {bidding.offers_count > 0 ? (
              <span className="ml-1 text-[10px] font-normal text-gray-500">({copy.offers(bidding.offers_count)})</span>
            ) : null}
          </Row>
        ) : null}
      </dl>

      {enquiry.next_step ? (
        <div className="rounded-lg bg-red-50/60 px-2.5 py-2">
          <p className="text-[10px] font-semibold uppercase tracking-wide text-[#A50E0E]">{copy.nextStep}</p>
          <p className="mt-0.5 whitespace-pre-line text-gray-700">{enquiry.next_step}</p>
        </div>
      ) : null}

      <div className="flex flex-wrap items-center gap-3 border-t border-gray-100 pt-2 text-[11px]">
        <ChatLink href={enquiry.href} arrow>
          {bidding?.is_live ? copy.watchBidding : copy.viewDetails}
        </ChatLink>
        {enquiry.order ? (
          <ChatLink href={enquiry.order.href} arrow>
            {copy.viewOrder}
            {enquiry.order.order_id ? ` ${enquiry.order.order_id}` : ""}
          </ChatLink>
        ) : null}
      </div>
    </BlockCard>
  );
}
