import { useApp } from "@/pages/app/AppContext";
import { Badge, cn } from "@/pages/app/components/ui";
import Countdown from "@/pages/app/components/bo/Countdown";
import type { InvestorFollowingCard } from "@/mocks/dshnInvestor";
import type { ScreenId } from "@/pages/app/types";

/** Maps a deal status to its dedicated request-details page. */
function detailsScreen(status: InvestorFollowingCard["status"]): ScreenId {
  switch (status) {
    case "new":
      return "invRequestDetailsNew";
    case "talking":
      return "invRequestDetails";
    case "negotiating":
      return "invRequestDetailsNegotiating";
    case "rejected":
      return "invRequestDetailsRejected";
    case "cancelled":
      return "invRequestDetailsCancelled";
    default:
      return "invRequestDetailsAgreed";
  }
}

function fmt(n: number) {
  return n.toLocaleString("en-US");
}

/**
 * One tappable follow-up card — it carries no action buttons; the whole card
 * opens its related page based on the deal status (all actions live there).
 */
export default function FollowingCard({ card }: { card: InvestorFollowingCard }) {
  const { navigate } = useApp();
  const c = card;
  const dim = c.status === "rejected" || c.status === "cancelled";
  const coinvestPayment = c.coinvest?.payment;
  const progress = c.coinvest ? Math.round((c.coinvest.collected / c.coinvest.target) * 100) : 0;

  const goCard = () => {
    if (c.kind === "coinvest") {
      if (coinvestPayment === "proofSent") {
        navigate("invPayment");
        return;
      }
      navigate("invCommitmentDetails", { requestId: c.id });
      return;
    }
    if (c.status === "counter") {
      navigate("invOfferCounter", { opportunityId: c.opportunityId, businessId: c.businessId });
      return;
    }
    navigate(detailsScreen(c.status), { requestId: c.id });
  };

  return (
    <div
      onClick={goCard}
      className={cn(
        "rounded-[18px] bg-background-100 border border-background-200 p-3.5 pb-4 cursor-pointer transition-colors hover:border-background-300",
        dim && "opacity-60",
      )}
    >
      <div className="flex items-center gap-3">
        <div className="w-12 h-12 rounded-full overflow-hidden bg-background-200 shrink-0">
          <img src={c.businessLogo} alt={c.businessName} className="w-full h-full object-cover object-top" />
        </div>
        <div className="flex-1 min-w-0">
          <h3 className="text-[14px] font-semibold text-foreground-950 truncate">{c.businessName}</h3>
          <p className="text-[11px] text-foreground-600 mt-0.5">{c.date}</p>
        </div>
        <i className="ri-arrow-left-s-line text-[20px] text-foreground-500 leading-none shrink-0" />
      </div>

      <div className="flex items-center gap-2 mt-3 flex-wrap">
        {c.kind === "coinvest" ? (
          <>
            <Badge tone="neutral">التزام استثمار تشاركي</Badge>
            <Badge tone={coinvestPayment === "due" ? "success" : "warn"}>
              {coinvestPayment === "due"
                ? "مطلوب السداد"
                : coinvestPayment === "proofSent"
                  ? "بانتظار تأكيد الاستلام"
                  : "قيد التفاوض"}
            </Badge>
          </>
        ) : (
          <Badge tone={c.statusTone}>{c.statusLabel}</Badge>
        )}
      </div>

      {c.status === "counter" && (
        <div className="mt-3 rounded-[12px] bg-secondary-50 border border-secondary-200 px-3 py-2.5 flex items-center gap-2 flex-wrap">
          <i className="ri-exchange-line text-[16px] text-secondary-800 leading-none" />
          <span className="text-[11.5px] font-semibold text-secondary-900">عرض مقابل</span>
          <span className="text-[12px] font-bold text-foreground-950">{fmt(c.counterAmount ?? 0)} ر.س</span>
          <span className="text-[12px] font-bold text-secondary-900">• {c.counterEquity}%</span>
        </div>
      )}

      <p className="text-[12.5px] text-foreground-700 mt-3 leading-relaxed">{c.message}</p>

      {c.kind === "coinvest" && c.coinvest && (
        <div className="mt-3">
          <div className="flex items-center justify-between text-[10.5px] text-foreground-600 mb-1.5">
            <span>تم جمع {progress}%</span>
            <span className="font-semibold text-foreground-900">
              {fmt(c.coinvest.collected)} / {fmt(c.coinvest.target)} ر.س
            </span>
          </div>
          <div className="h-2 rounded-full bg-accent-100 overflow-hidden">
            <div className="h-full bg-accent-500 rounded-full" style={{ width: `${progress}%` }} />
          </div>
          <div className="mt-3">
            <Countdown target={c.coinvest.endAt} />
          </div>
        </div>
      )}

      <div className="grid grid-cols-2 gap-2.5 mt-3">
        <div className="rounded-[12px] bg-background-200/70 p-2.5">
          <p className="text-[10px] text-foreground-600">قيمة العرض</p>
          <p className="text-[13px] font-bold text-foreground-950 mt-0.5">{fmt(c.amount)} ر.س</p>
        </div>
        <div className="rounded-[12px] bg-accent-100 p-2.5">
          <p className="text-[10px] text-accent-800">النسبة</p>
          <p className="text-[13px] font-bold text-accent-900 mt-0.5">{c.equity}%</p>
        </div>
      </div>
    </div>
  );
}