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

const DAY = 86400000;
const NOW = Date.now();
const TARGETS: Record<string, number> = {
  "op-inv-1": NOW + 50 * DAY,
  "op-inv-3": NOW + 70 * DAY,
};

const CATS = ["عقارات", "سيارات", "علامات تجارية/وكالات", "ابتكارات"];
const SORTS = ["الأعلى قيمة", "الأقل قيمة", "الأعلى نسبة", "الأقل نسبة", "الأعلى تقييمًا", "الأقل تقييمًا"];

export default function InvOpportunities() {
  const { t, navigate } = useWeb();
  const [search, setSearch] = useState("");
  const [cat, setCat] = useState("");
  const [sort, setSort] = useState("");

  const list = useMemo(() => {
    let out = investorOpportunities.filter((o) =>
      [o.businessName, o.category, o.businessActivity].some((v) => v.includes(search.trim())),
    );
    if (cat) out = out.filter((o) => o.category === cat);
    if (sort === "الأعلى قيمة") out = [...out].sort((a, b) => b.amount - a.amount);
    if (sort === "الأقل قيمة") out = [...out].sort((a, b) => a.amount - b.amount);
    if (sort === "الأعلى نسبة") out = [...out].sort((a, b) => b.equity - a.equity);
    if (sort === "الأقل نسبة") out = [...out].sort((a, b) => a.equity - b.equity);
    if (sort === "الأعلى تقييمًا") out = [...out].sort((a, b) => b.valuation - a.valuation);
    if (sort === "الأقل تقييمًا") out = [...out].sort((a, b) => a.valuation - b.valuation);
    return out;
  }, [search, cat, sort]);

  const reset = () => {
    setCat("");
    setSort("");
  };

  return (
    <div className="animate-fade-in">
      <WebPageHeader title={t("navOpportunities")} desc={`${list.length} ${t("results")}`} crumb="الفرص الاستثمارية" />
      <Container className="py-8">
        <div className="flex flex-col lg:flex-row gap-8 items-start">
          <aside className="w-full lg:w-[280px] shrink-0 ">
            <WCard className="p-5">
              <div className="flex items-center gap-2 h-11 px-3.5 rounded-[12px] bg-background-50 border border-background-200 mb-5 focus-within:border-foreground-400 transition-colors">
                <i className="ri-search-line text-[18px] text-foreground-500 leading-none" />
                <input
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder="ابحث عن فرصة"
                  className="flex-1 bg-transparent text-[13.5px] text-foreground-950 placeholder:text-foreground-500 outline-none font-body"
                />
              </div>
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-[15px] font-bold text-foreground-950">{t("filters")}</h3>
                <button type="button" onClick={reset} className="text-[12px] text-foreground-600 hover:text-foreground-950 cursor-pointer">
                  {t("clearFilters")}
                </button>
              </div>
              <Group title="القطاع" options={CATS} value={cat} onChange={setCat} />
              <Group title="الترتيب" options={SORTS} value={sort} onChange={setSort} last />
            </WCard>
          </aside>

          <div className="flex-1 min-w-0 w-full">
            {list.length === 0 ? (
              <WCard className="py-16 text-center">
                <p className="text-[14px] text-foreground-600">لا توجد فرص مطابقة — جرّب تعديل الفلاتر.</p>
              </WCard>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-5">
                {list.map((op) => {
                  const progress = op.collected && op.target ? Math.round((op.collected / op.target) * 100) : 0;
                  return (
                    <WCard key={op.id} className="p-5 flex flex-col" onClick={() => navigate("invOpp", { opportunityId: op.id })}>
                      <div className="flex items-center gap-3">
                        <div className="w-12 h-12 rounded-full overflow-hidden bg-background-200 shrink-0">
                          <img src={op.businessLogo} alt={op.businessName} className="w-full h-full object-cover object-top" />
                        </div>
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center gap-1.5">
                            <p className="text-[14.5px] font-semibold text-foreground-950 truncate">{op.businessName}</p>
                            {op.verified && <i className="ri-verified-badge-fill text-accent-700 text-[14px] leading-none" />}
                          </div>
                          <p className="text-[11.5px] text-foreground-600">{op.businessActivity} • {op.businessCity}</p>
                        </div>
                      </div>

                      <div className="mt-4 space-y-2">
                        <div className="flex items-center justify-between text-[12.5px]">
                          <span className="text-foreground-600">{t("requiredAmount")}</span>
                          <span className="font-bold text-foreground-950">{fmt(op.amount)} ر.س</span>
                        </div>
                        <div className="flex items-center justify-between text-[12.5px]">
                          <span className="text-foreground-600">{t("offeredEquity")}</span>
                          <span className="font-bold text-accent-700">{op.equity}%</span>
                        </div>
                        <div className="flex items-center justify-between text-[12.5px]">
                          <span className="text-foreground-600">تقييم المنشأة</span>
                          <span className="font-bold text-foreground-950">{fmt(op.valuation)}</span>
                        </div>
                      </div>

                      {op.coinvest && op.collected !== undefined && op.target !== undefined && (
                        <div className="mt-4">
                          <div className="flex items-center justify-between text-[11px] mb-1.5">
                            <span className="text-foreground-600">استثمار تشاركي · {progress}%</span>
                            <span className="font-semibold text-foreground-900">{fmt(op.collected)} / {fmt(op.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>
                      )}

                      <div className="mt-4 pt-3 border-t border-background-200 flex items-center gap-2 flex-wrap">
                        <StatusPill tone="info" icon="ri-price-tag-3-line">{op.category}</StatusPill>
                        <StatusPill tone="warn">مرحلة: {op.stage}</StatusPill>
                      </div>

                      {op.timed && TARGETS[op.id] && (
                        <div className="mt-4">
                          <p className="text-[11px] text-foreground-600 mb-2">تنتهي الفرصة خلال</p>
                          <Countdown target={TARGETS[op.id]} compact />
                        </div>
                      )}

                      <WBtn size="sm" className="w-full mt-4" icon="ri-arrow-left-line">
                        عرض الفرصة
                      </WBtn>
                    </WCard>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </Container>
    </div>
  );
}

function Group({
  title,
  options,
  value,
  onChange,
  last,
}: {
  title: string;
  options: string[];
  value: string;
  onChange: (v: string) => void;
  last?: boolean;
}) {
  return (
    <div className={cn("pb-4 mb-4", !last && "border-b border-background-200")}>
      <p className="text-[12.5px] font-bold text-foreground-800 mb-2.5">{title}</p>
      <div className="flex flex-wrap gap-2">
        {options.map((o) => (
          <button
            key={o}
            type="button"
            onClick={() => onChange(value === o ? "" : o)}
            className={cn(
              "rounded-full px-3 py-1.5 text-[12px] font-medium cursor-pointer transition-colors whitespace-nowrap",
              value === o ? "bg-primary-500 text-background-50" : "bg-background-50 border border-background-200 text-foreground-700 hover:border-background-300",
            )}
          >
            {o}
          </button>
        ))}
      </div>
    </div>
  );
}