import { useState } from "react";
import { useApp } from "../AppContext";
import { businesses } from "@/mocks/dshn";
import { BusinessRow } from "../components/BusinessCard";
import { EmptyState, SearchInput, cn } from "../components/ui";

interface FilterDef {
  id: string;
  label: string;
  options: string[];
}

const FILTERS: FilterDef[] = [
  { id: "activity", label: "النشاط", options: ["أغذية ومشروبات", "إلكترونيات", "أزياء", "منتجات تجميل", "منتجات صناعية", "أثاث", "خدمات", "منتجات رقمية"] },
  { id: "city", label: "المدينة", options: ["الرياض", "جدة", "الدمام"] },
  { id: "value", label: "القيمة", options: ["الأعلى قيمة", "الأقل قيمة"] },
  { id: "revenue", label: "حجم الإيرادات", options: ["الأعلى مبيعات", "الأقل مبيعات"] },
  { id: "stage", label: "مرحلة المشروع", options: ["ناشئة", "في مرحلة النمو", "مستقرة"] },
];

export default function Businesses() {
  const { navigate } = useApp();
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState<string | null>(null);
  const [selected, setSelected] = useState<Record<string, string>>({});

  let list = businesses.filter((b) =>
    [b.name, b.activity, b.city].some((v) => v.includes(query.trim())),
  );
  if (selected.activity) list = list.filter((b) => b.activity === selected.activity);
  if (selected.city) list = list.filter((b) => b.city === selected.city);
  if (selected.value === "الأعلى قيمة") list = [...list].sort((a, b) => b.estimatedValue - a.estimatedValue);
  if (selected.value === "الأقل قيمة") list = [...list].sort((a, b) => a.estimatedValue - b.estimatedValue);
  if (selected.revenue === "الأعلى مبيعات") list = [...list].sort((a, b) => b.annualSales - a.annualSales);
  if (selected.revenue === "الأقل مبيعات") list = [...list].sort((a, b) => a.annualSales - b.annualSales);

  const activeCount = Object.keys(selected).length;

  return (
    <div className="pb-6">
      <div className="px-4 flex items-center justify-between gap-3">
        <h1 className="text-[24px] font-bold text-foreground-950">المنشآت</h1>
        <button
          type="button"
          onClick={() => navigate("map")}
          className="flex items-center gap-1.5 h-10 px-3.5 rounded-full bg-background-100 border border-background-200 text-[12.5px] font-semibold text-foreground-950 whitespace-nowrap cursor-pointer hover:border-foreground-300"
        >
          <i className="ri-map-2-line text-[16px] leading-none" />
          عرض على الخريطة
        </button>
      </div>

      <div className="px-4 mt-4">
        <SearchInput value={query} onChange={setQuery} placeholder="ابحث عن منشأة" />
      </div>

      <div className="flex gap-2 overflow-x-auto no-scrollbar px-4 mt-4">
        {FILTERS.map((f) => {
          const active = !!selected[f.id];
          return (
            <button
              key={f.id}
              type="button"
              onClick={() => setOpen((o) => (o === f.id ? null : f.id))}
              className={cn(
                "flex items-center gap-1 rounded-full px-3.5 py-2 text-[12.5px] font-medium whitespace-nowrap cursor-pointer transition-colors",
                active
                  ? "bg-primary-500 text-background-50"
                  : "bg-background-100 border border-background-200 text-foreground-700 hover:border-foreground-300",
              )}
            >
              {active ? selected[f.id] : f.label}
              <i className={cn("ri-arrow-down-s-line text-[15px] leading-none transition-transform", open === f.id && "rotate-180")} />
            </button>
          );
        })}
        {activeCount > 0 && (
          <button
            type="button"
            onClick={() => setSelected({})}
            className="flex items-center gap-1 rounded-full px-3.5 py-2 text-[12.5px] font-medium text-danger-600 whitespace-nowrap cursor-pointer"
          >
            <i className="ri-close-circle-line text-[15px] leading-none" />
            مسح
          </button>
        )}
      </div>

      {open && (
        <div className="mx-4 mt-3 rounded-[20px] bg-background-100 border border-background-200 p-3 animate-fade-in">
          <div className="flex flex-wrap gap-2">
            {FILTERS.find((f) => f.id === open)?.options.map((opt) => (
              <button
                key={opt}
                type="button"
                onClick={() => {
                  setSelected((s) => {
                    const next = { ...s };
                    if (next[open] === opt) delete next[open];
                    else next[open] = opt;
                    return next;
                  });
                  setOpen(null);
                }}
                className={cn(
                  "rounded-full px-3.5 py-2 text-[12.5px] font-medium cursor-pointer transition-colors",
                  selected[open] === opt
                    ? "bg-primary-500 text-background-50"
                    : "bg-background-200 text-foreground-700 hover:bg-background-300",
                )}
              >
                {opt}
              </button>
            ))}
          </div>
        </div>
      )}

      <div className="px-4 mt-4">
        {list.length === 0 ? (
          <EmptyState
            icon="ri-search-eye-line"
            title="لا توجد نتائج مطابقة"
            desc="جرّب تعديل الفلاتر أو البحث باسم منشأة آخر."
            actionLabel="مسح الفلاتر"
            onAction={() => {
              setQuery("");
              setSelected({});
            }}
          />
        ) : (
          <div className="space-y-3">
            {list.map((b) => (
              <BusinessRow
                key={b.id}
                business={b}
                onClick={() => navigate("business", { businessId: b.id })}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}