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

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

const CATS = ["عقارات", "سيارات", "علامات تجارية/وكالات", "ابتكارات", "وغيرها"];

const FILTERS: { key: string; label: string; options: string[] }[] = [
  { key: "amount", label: "قيمة الاستثمار", options: ["أقل من 500 ألف", "500 ألف - 1 مليون", "أكثر من 1 مليون"] },
  { key: "sector", label: "القطاع", options: CATS },
  { key: "equity", label: "نسبة الاستثمار", options: ["أقل من 15%", "15% - 25%", "أكثر من 25%"] },
  { key: "valuation", label: "قيمة المنشأة", options: ["أقل من 2 مليون", "2 - 5 مليون", "أكثر من 5 مليون"] },
];

export default function Opportunities() {
  const { navigate } = useWeb();
  const [search, setSearch] = useState("");
  const [cat, setCat] = useState("الكل");
  const [values, setValues] = useState<Record<string, string>>({});
  const [openFilter, setOpenFilter] = useState<string | null>(null);

  const list = useMemo(() => {
    return investorOpportunities.filter((o) => {
      if (search && ![o.businessName, o.category, o.businessActivity].some((v) => v.includes(search.trim()))) return false;
      if (cat !== "الكل" && o.category !== cat) return false;
      if (values.amount === "أقل من 500 ألف" && o.amount >= 500000) return false;
      if (values.amount === "500 ألف - 1 مليون" && (o.amount < 500000 || o.amount > 1000000)) return false;
      if (values.amount === "أكثر من 1 مليون" && o.amount <= 1000000) return false;
      if (values.sector && o.category !== values.sector) return false;
      if (values.equity === "أقل من 15%" && o.equity >= 15) return false;
      if (values.equity === "15% - 25%" && (o.equity < 15 || o.equity > 25)) return false;
      if (values.equity === "أكثر من 25%" && o.equity <= 25) return false;
      if (values.valuation === "أقل من 2 مليون" && o.valuation >= 2000000) return false;
      if (values.valuation === "2 - 5 مليون" && (o.valuation < 2000000 || o.valuation > 5000000)) return false;
      if (values.valuation === "أكثر من 5 مليون" && o.valuation <= 5000000) return false;
      return true;
    });
  }, [search, cat, values]);

  const setFilter = (key: string, val: string) => {
    setValues((v) => ({ ...v, [key]: v[key] === val ? "" : val }));
    setOpenFilter(null);
  };

  const pills = ["الكل", ...CATS];

  return (
    <div className="animate-fade-in">
      <WebPageHeader title="الفرص الاستثمارية" desc={`${list.length} فرصة`} crumb="الفرص الاستثمارية" />

      <Container className="py-8">
        {/* search */}
        <div className="flex items-center gap-2 h-12 px-4 rounded-[16px] bg-background-100 border border-background-200 focus-within:border-foreground-400 transition-colors max-w-[560px]">
          <i className="ri-search-line text-[19px] text-foreground-500 leading-none" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="ابحث عن فرصة"
            className="flex-1 bg-transparent text-[14px] text-foreground-950 placeholder:text-foreground-500 outline-none font-body"
          />
        </div>

        {/* category chips */}
        <div className="flex items-center gap-2 flex-wrap mt-5">
          {pills.map((c) => (
            <button
              key={c}
              type="button"
              onClick={() => setCat(c)}
              className={cn(
                "rounded-full h-10 px-4 text-[13px] font-medium whitespace-nowrap cursor-pointer transition-colors",
                cat === c ? "bg-primary-500 text-background-50" : "bg-background-100 border border-background-200 text-foreground-700 hover:border-background-300",
              )}
            >
              {c}
            </button>
          ))}
        </div>

        {/* filter chips */}
        <div className="flex items-center gap-2 flex-wrap mt-3">
          {FILTERS.map((f) => {
            const selected = values[f.key];
            return (
              <div key={f.key} className="relative">
                <button
                  type="button"
                  onClick={() => setOpenFilter((o) => (o === f.key ? null : f.key))}
                  className={cn(
                    "rounded-full h-10 px-4 text-[12.5px] font-medium whitespace-nowrap cursor-pointer transition-colors flex items-center gap-1.5",
                    selected ? "bg-accent-500 text-foreground-950" : "bg-background-100 border border-background-200 text-foreground-700 hover:border-background-300",
                  )}
                >
                  {selected || f.label}
                  <i className={cn(openFilter === f.key ? "ri-arrow-up-s-line" : "ri-arrow-down-s-line", "text-[16px] leading-none")} />
                </button>
                {openFilter === f.key && (
                  <div className="absolute z-30 top-[calc(100%+8px)] start-0 w-56 bg-background-100 border border-background-200 rounded-[16px] p-2">
                    <button
                      type="button"
                      onClick={() => { setValues((v) => ({ ...v, [f.key]: "" })); setOpenFilter(null); }}
                      className="w-full h-9 px-3 rounded-[10px] text-start text-[13px] text-foreground-600 hover:bg-background-200 cursor-pointer"
                    >
                      الكل
                    </button>
                    {f.options.map((o) => (
                      <button
                        key={o}
                        type="button"
                        onClick={() => setFilter(f.key, o)}
                        className={cn(
                          "w-full h-9 px-3 rounded-[10px] text-start text-[13px] cursor-pointer hover:bg-background-200",
                          selected === o ? "text-foreground-950 font-semibold" : "text-foreground-700",
                        )}
                      >
                        {o}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {/* grid */}
        <div className="mt-8">
          {list.length === 0 ? (
            <WCard className="py-20 text-center">
              <div className="w-16 h-16 rounded-full bg-background-200 flex items-center justify-center mx-auto mb-5">
                <i className="ri-lightbulb-line text-[30px] text-foreground-500 leading-none" />
              </div>
              <p className="text-[15px] font-semibold text-foreground-950">لا توجد فرص مطابقة</p>
              <p className="text-[13px] text-foreground-600 mt-1.5">جرّب تعديل البحث أو الفلاتر.</p>
            </WCard>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-5">
              {list.map((op, index) => {
                const progress = op.collected && op.target ? Math.round((op.collected / op.target) * 100) : 0;
                const target = NOW + (50 + index * 17) * DAY;
                return (
                  <WCard key={op.id} className="p-5 flex flex-col" onClick={() => navigate("opportunity", { 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-[15px] font-semibold text-foreground-950">{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">
                      <StatusPill tone="info" icon="ri-price-tag-3-line">{op.category}</StatusPill>
                    </div>

                    <div className="mt-4 grid grid-cols-2 gap-2.5">
                      <div className="rounded-[14px] bg-background-200 px-2.5 py-3 text-center">
                        <p className="text-[11px] text-foreground-600 whitespace-nowrap">قيمة الاستثمار</p>
                        <p className="text-[14px] font-bold text-foreground-950 mt-1 whitespace-nowrap">{fmt(op.amount)} ر.س</p>
                      </div>
                      <div className="rounded-[14px] bg-secondary-100 px-2.5 py-3 text-center">
                        <p className="text-[11px] font-semibold text-secondary-900 whitespace-nowrap">النسبة المعروضة</p>
                        <p className="text-[16px] font-bold text-secondary-900 leading-tight mt-1">{op.equity}%</p>
                      </div>
                    </div>

                    <div className="mt-3 flex items-center justify-between gap-2 text-[12.5px]">
                      <span className="text-foreground-600 whitespace-nowrap">تقييم المنشأة</span>
                      <span className="font-bold text-foreground-950 whitespace-nowrap">{fmt(op.valuation)} ر.س</span>
                    </div>

                    {op.coinvest && op.collected !== undefined && op.target !== undefined && (
                      <div className="mt-4">
                        <div className="flex items-center justify-between text-[11.5px] mb-1.5">
                          <span className="text-accent-800 font-semibold">تم جمع {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>
                        {op.timed && (
                          <div className="mt-3">
                            <Countdown target={target} compact />
                          </div>
                        )}
                      </div>
                    )}

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