import { useState } from "react";
import { useApp } from "@/pages/app/AppContext";
import { BackHeader, Badge, Btn, cn } from "@/pages/app/components/ui";
import Countdown from "@/pages/app/components/bo/Countdown";
import { Field, KvRow, Sheet } from "@/pages/app/components/bo/BoUI";
import { investorOpportunities } from "@/mocks/dshnInvestor";

/** Live countdown target: 49 days 23:58:09 from first render. */
const COUNTDOWN_MS = (49 * 24 * 60 * 60 + 23 * 60 * 60 + 58 * 60 + 9) * 1000;

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

function fmtPct(n: number) {
  return String(Math.round(n * 100) / 100);
}

/**
 * Co-Investment Pool Commitment — the investor pledges a partial amount
 * toward a shared opportunity instead of the whole amount alone.
 *
 * A single body that renders all three form states via `initialAmount`:
 *  - empty  ("")        → share "—", button disabled
 *  - valid  ("100000")  → share 3%, black button
 *  - error  ("250000")  → red border + red message, button disabled
 * The confirmation bottom sheet opens on top of the valid state.
 */
export default function CoinvestCommitForm({ initialAmount = "100000" }: { initialAmount?: string }) {
  const { goBack, navigate } = useApp();
  const opp = investorOpportunities.find((o) => o.id === "op-inv-1") ?? investorOpportunities[0];
  const target = opp.target ?? opp.amount;
  const collected = opp.collected ?? 0;
  const remaining = target - collected;
  const progress = Math.round((collected / target) * 100);
  const offeredEquity = opp.equity;

  const [amount, setAmount] = useState(initialAmount);
  const [sheetOpen, setSheetOpen] = useState(false);
  const [deadline] = useState(() => Date.now() + COUNTDOWN_MS);

  const value = Number(amount) || 0;
  const exceeds = value > remaining;
  const valid = value > 0 && !exceeds;
  const share = value > 0 ? (value / target) * offeredEquity : 0;

  const onAmount = (raw: string) => {
    setAmount(raw.replace(/\D/g, "").slice(0, 9));
  };

  return (
    <div className="flex min-h-full flex-col bg-background-50">
      <BackHeader title="تقديم التزام استثماري" onBack={goBack} />

      <div className="flex-1 px-4 py-4 space-y-4">
        {/* Business summary */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4">
          <div className="flex items-center gap-3">
            <div className="w-14 h-14 rounded-full overflow-hidden bg-background-200 shrink-0">
              <img
                src={opp.businessLogo}
                alt={opp.businessName}
                className="w-full h-full object-cover object-top"
              />
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-1.5">
                <h2 className="text-[16px] font-bold text-foreground-950 leading-tight">
                  {opp.businessName}
                </h2>
                <i className="ri-verified-badge-fill text-accent-600 text-[15px] leading-none shrink-0" />
              </div>
              <p className="text-[11.5px] text-foreground-600 mt-0.5 leading-relaxed">
                {opp.businessActivity} • {opp.businessCity}
              </p>
            </div>
          </div>
          <div className="mt-3">
            <Badge tone="mint" icon="ri-group-line">
              استثمار تشاركي
            </Badge>
          </div>
        </div>

        {/* Opportunity status */}
        <div className="rounded-[20px] bg-background-100 border border-background-200 p-4">
          <div className="flex items-center justify-between gap-3">
            <span className="text-[13px] font-semibold text-foreground-950 whitespace-nowrap">
              تم جمع {progress}%
            </span>
            <span className="text-[13px] font-bold text-foreground-950 whitespace-nowrap">
              {fmt(collected)} / {fmt(target)} ر.س
            </span>
          </div>

          <div className="mt-2.5 h-3 rounded-full bg-accent-100 overflow-hidden">
            <div className="h-full bg-accent-500 rounded-full" style={{ width: `${progress}%` }} />
          </div>

          <p className="text-[11.5px] text-foreground-600 mt-2">
            المبلغ المتبقي: {fmt(remaining)} ر.س
          </p>

          <div className="mt-4">
            <p className="text-[11.5px] text-foreground-600 mb-2">تنتهي الفرصة خلال</p>
            <Countdown target={deadline} />
          </div>
        </div>

        {/* Target + offered equity tiles */}
        <div className="grid grid-cols-2 gap-3">
          <div className="rounded-[18px] bg-background-100 border border-background-200 p-4">
            <p className="text-[11px] text-foreground-600 leading-relaxed">المبلغ المستهدف</p>
            <p className="text-[15px] font-bold text-foreground-950 mt-1.5 leading-tight">
              {fmt(target)} ر.س
            </p>
          </div>
          <div className="rounded-[18px] bg-secondary-50 border border-secondary-200 p-4">
            <p className="text-[11px] text-secondary-900/80 leading-relaxed">نسبة الملكية المعروضة</p>
            <p className="text-[15px] font-bold text-secondary-800 mt-1.5 leading-tight">
              {offeredEquity}%
            </p>
          </div>
        </div>

        {/* Amount input */}
        <Field
          label="المبلغ الذي أرغب بالالتزام به (ر.س)"
          required
          hint={exceeds ? undefined : `أدخل أي مبلغ حتى ${fmt(remaining)} ر.س`}
        >
          <input
            inputMode="numeric"
            dir="rtl"
            value={amount ? fmt(Number(amount)) : ""}
            onChange={(e) => onAmount(e.target.value)}
            placeholder="0"
            className={cn(
              "w-full h-[52px] px-4 rounded-[13px] bg-background-100 border text-[16px] font-semibold text-foreground-950 placeholder:text-foreground-500 outline-none transition-colors font-body",
              exceeds
                ? "border-danger-500 focus:border-danger-500"
                : "border-background-200 focus:border-foreground-400",
            )}
          />
        </Field>

        {exceeds && (
          <p className="text-[12px] text-danger-600 -mt-2 leading-relaxed">
            المبلغ يتجاوز المتبقي من الفرصة ({fmt(remaining)} ر.س)
          </p>
        )}

        {/* Auto-calculated share */}
        <div className="rounded-[20px] bg-accent-50 border border-accent-200 p-4">
          <p className="text-[12px] text-foreground-600">نصيبك المتوقع</p>
          <p className="text-[30px] font-bold text-accent-800 mt-1 leading-none">
            {value > 0 ? `${fmtPct(share)}%` : "—"}
          </p>
          {value > 0 && (
            <p className="text-[12px] text-foreground-700 mt-2.5" dir="rtl">
              {fmt(value)} ÷ {fmt(target)} × {offeredEquity}% = {fmtPct(share)}%
            </p>
          )}
          <p className="text-[11px] text-foreground-500 mt-2 leading-relaxed">
            النصيب نهائي بعد الاتفاق مع صاحب المنشأة
          </p>
        </div>

        {/* Info banner */}
        <div className="flex items-start gap-2.5 rounded-[16px] bg-secondary-50 border border-secondary-200 px-4 py-3.5">
          <i className="ri-information-line text-[18px] text-secondary-800 leading-none shrink-0 mt-0.5" />
          <p className="text-[12px] text-secondary-900 leading-relaxed">
            التزامك تعهد مبدئي. لن يُطلب منك السداد إلا بعد إغلاق الفرصة، ويمكنك إلغاء التزامك قبل ذلك.
          </p>
        </div>
      </div>

      <div className="sticky bottom-0 z-30 mt-auto p-4 bg-background-50/95 backdrop-blur border-t border-background-200/70">
        <Btn full disabled={!valid} onClick={() => setSheetOpen(true)}>
          تقديم الالتزام
        </Btn>
      </div>

      {/* Confirmation bottom sheet */}
      <Sheet open={sheetOpen} onClose={() => setSheetOpen(false)}>
        <h3 className="text-[17px] font-bold text-foreground-950 text-center">تأكيد الالتزام</h3>
        <div className="mt-4 rounded-[16px] bg-background-100 border border-background-200 p-4 space-y-3.5">
          <KvRow label="المبلغ" value={`${fmt(value)} ر.س`} strong />
          <div className="h-px bg-background-200" />
          <KvRow label="النصيب المتوقع" value={`${fmtPct(share)}%`} strong />
          <div className="h-px bg-background-200" />
          <KvRow label="المنشأة" value={opp.businessName} strong />
        </div>
        <div className="mt-4 space-y-2.5">
          <Btn
            full
            onClick={() => {
              setSheetOpen(false);
              navigate("invCoinvestSuccess", { opportunityId: opp.id, amount: String(value) });
            }}
          >
            تأكيد
          </Btn>
          <Btn full variant="secondary" onClick={() => setSheetOpen(false)}>
            تراجع
          </Btn>
        </div>
      </Sheet>
    </div>
  );
}