import { investorOpportunities } from "@/mocks/dshnInvestor";
import { useWeb } from "@/pages/web/WebContext";
import { Container, WCard, WBtn, StatusPill, fmt } from "@/pages/web/WebUI";
import Countdown from "@/pages/app/components/bo/Countdown";

const DAY = 86400000;
const NOW = Date.now();

function targetFor(index: number) {
  return NOW + (50 + index * 17) * DAY;
}

export default function InvOpportunityDetail() {
  const { params, navigate, goBack, role, requireAuth } = useWeb();
  const opp = investorOpportunities.find((o) => o.id === params.opportunityId) ?? investorOpportunities[0];
  const index = investorOpportunities.findIndex((o) => o.id === opp.id);
  const progress = opp.collected && opp.target ? Math.round((opp.collected / opp.target) * 100) : 0;
  const isInvestor = role === "investor";
  const isGuest = !role;

  return (
    <div className="animate-fade-in">
      <Container className="py-8">
        <button
          type="button"
          onClick={goBack}
          className="inline-flex items-center gap-2 text-[13px] font-medium text-foreground-600 hover:text-foreground-950 cursor-pointer mb-5"
        >
          <i className="ri-arrow-right-line text-[17px] leading-none" />
          رجوع
        </button>

        <div className="flex flex-col md:flex-row gap-6 items-start">
          {/* MAIN column (right side in RTL) */}
          <div className="w-full min-w-0 flex-1 space-y-6">
            <WCard className="p-6">
              <div className="flex items-center gap-4">
                <div className="w-16 h-16 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-2 flex-wrap">
                    <h1 className="text-[22px] font-bold text-foreground-950 font-heading break-words">{opp.businessName}</h1>
                    {opp.verified && <i className="ri-verified-badge-fill text-accent-700 text-[18px] leading-none" />}
                  </div>
                  <p className="text-[13px] text-foreground-600 mt-0.5">{opp.businessActivity} • {opp.businessCity}</p>
                </div>
              </div>
              <div className="mt-4 flex items-center gap-2 flex-wrap">
                <StatusPill tone="info" icon="ri-price-tag-3-line">{opp.category}</StatusPill>
                <StatusPill tone="warn">مرحلة: {opp.stage}</StatusPill>
              </div>
            </WCard>

            <WCard className="p-6">
              <h2 className="text-[17px] font-bold text-foreground-950 mb-3">استخدام المبلغ</h2>
              <p className="text-[14px] text-foreground-700 leading-relaxed">{opp.useOfFunds}</p>
            </WCard>

            <WCard className="p-6">
              <h2 className="text-[17px] font-bold text-foreground-950 mb-3">نبذة عن الفرصة</h2>
              <p className="text-[14px] text-foreground-700 leading-relaxed">{opp.description}</p>
            </WCard>

            <WCard className="p-6">
              <h2 className="text-[17px] font-bold text-foreground-950 mb-4">المستندات</h2>
              <div className="space-y-2.5">
                {opp.documents.map((d) => (
                  <div key={d} className="flex items-center gap-3 rounded-[14px] bg-background-50 border border-background-200 px-4 py-3.5">
                    <i className="ri-file-pdf-2-line text-[21px] text-danger-500 leading-none shrink-0" />
                    <span className="text-[13px] text-foreground-800 flex-1 break-words">{d}</span>
                    <button type="button" aria-label="تحميل" className="w-9 h-9 rounded-full flex items-center justify-center hover:bg-background-200 cursor-pointer shrink-0">
                      <i className="ri-download-2-line text-[18px] text-foreground-600 leading-none" />
                    </button>
                  </div>
                ))}
              </div>
            </WCard>
          </div>

          {/* SIDE column (left side in RTL) */}
          <div className="w-full md:w-[360px] shrink-0">
            <WCard className="p-6">
              <div className="space-y-3.5">
                <StatRow label="مبلغ الاستثمار" value={`${fmt(opp.amount)} ر.س`} />
                <StatRow label="النسبة المعروضة" value={`${opp.equity}%`} accent />
                <StatRow label="تقييم المنشأة" value={`${fmt(opp.valuation)} ر.س`} />
              </div>

              {opp.coinvest && opp.collected !== undefined && opp.target !== undefined && (
                <div className="mt-5 pt-5 border-t border-background-200">
                  <div className="flex items-center gap-2 mb-3">
                    <i className="ri-group-line text-[19px] text-accent-700 leading-none" />
                    <h3 className="text-[15px] font-bold text-foreground-950">استثمار تشاركي</h3>
                  </div>
                  <div className="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-[12.5px] text-foreground-600 mt-2">
                    تم جمع {progress}% — {fmt(opp.collected)} / {fmt(opp.target)} ر.س
                  </p>
                  {opp.timed && (
                    <div className="mt-4">
                      <p className="text-[12px] text-foreground-600 mb-2">تنتهي الفرصة خلال</p>
                      <Countdown target={targetFor(index)} />
                    </div>
                  )}
                </div>
              )}

              <div className="mt-6 space-y-3">
                <WBtn
                  full
                  variant="secondary"
                  icon="ri-store-2-line"
                  onClick={() => navigate("business", { businessId: opp.businessId })}
                >
                  عرض صفحة المنشأة
                </WBtn>

                {isGuest && (
                  <WBtn
                    full
                    icon="ri-user-star-line"
                    onClick={() => requireAuth("investor", () => navigate("invOffer", { opportunityId: opp.id }))}
                  >
                    سجّل كمستثمر لتقديم عرض
                  </WBtn>
                )}

                {isInvestor && (
                  <WBtn full icon="ri-hand-coin-line" onClick={() => navigate("invOffer", { opportunityId: opp.id })}>
                    تقديم عرض استثمار
                  </WBtn>
                )}

                {!isGuest && !isInvestor && (
                  <div className="rounded-[14px] bg-background-100 border border-background-200 px-4 py-3 text-center text-[12.5px] text-foreground-600 leading-relaxed">
                    تقديم العروض متاح لحسابات المستثمرين
                  </div>
                )}
              </div>
            </WCard>
          </div>
        </div>
      </Container>
    </div>
  );
}

function StatRow({ label, value, accent }: { label: string; value: string; accent?: boolean }) {
  return (
    <div className="flex items-center justify-between gap-3">
      <span className="text-[13px] text-foreground-600">{label}</span>
      <span className={accent ? "text-[16px] font-bold text-accent-700" : "text-[16px] font-bold text-foreground-950"}>
        {value}
      </span>
    </div>
  );
}