import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useBoardAssociations } from "@/contexts/BoardAssociationContext";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Loader2, ExternalLink, FileText, BookOpen, Search, Link2, Landmark, Scale, ShieldCheck, Folder } from "lucide-react";

type BoardResource = {
  id: string;
  title: string;
  category: string;
  resource_type: string;
  url: string | null;
  file_url: string | null;
  description: string | null;
  associations?: { name: string } | null;
};

const STATIC_LINKS = [
  { title: "Community Associations Institute (CAI)", url: "https://www.caionline.org", description: "Industry resources, education, and advocacy for community associations.", icon: Landmark },
  { title: "HOA Laws by State", url: "https://www.hopb.co/hoa-laws", description: "Comprehensive directory of HOA statutes and regulations by state.", icon: Scale },
  { title: "Fair Housing Act Overview", url: "https://www.hud.gov/program_offices/fair_housing_equal_opp/fair_housing_act_overview", description: "U.S. Department of Housing and Urban Development fair housing guidelines.", icon: ShieldCheck },
  { title: "Robert's Rules of Order", url: "https://robertsrules.com", description: "Parliamentary procedure guide for running effective board meetings.", icon: BookOpen },
];

const CATEGORY_ICONS: Record<string, typeof Folder> = {
  Legal: Scale,
  Finance: Landmark,
  Onboarding: BookOpen,
  Governance: ShieldCheck,
};

export default function BoardResourcesPage() {
  const { associationIds, loading: assocLoading } = useBoardAssociations();
  const [resources, setResources] = useState<BoardResource[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");

  useEffect(() => {
    if (assocLoading || associationIds.length === 0) return;
    (async () => {
      setLoading(true);
      const { data } = await supabase
        .from("board_resources")
        .select("id, title, category, resource_type, url, file_url, description, associations(name)")
        .in("association_id", associationIds)
        .eq("is_active", true)
        .order("category")
        .order("sort_order");
      setResources((data as BoardResource[]) || []);
      setLoading(false);
    })();
  }, [associationIds, assocLoading]);

  const q = search.toLowerCase();
  const filtered = resources.filter(
    (r) => r.title.toLowerCase().includes(q) || r.category.toLowerCase().includes(q) || (r.description || "").toLowerCase().includes(q)
  );

  const categories = [...new Set(filtered.map((r) => r.category))];

  if (assocLoading || loading) {
    return (
      <div className="flex justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="max-w-5xl mx-auto space-y-8">
      <div>
        <h1 className="text-2xl font-bold flex items-center gap-2">
          <BookOpen className="h-6 w-6 text-primary" /> Board Resources
        </h1>
        <p className="text-sm text-muted-foreground mt-1">Helpful links, reading materials, and documents for board members.</p>
      </div>

      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input placeholder="Search resources..." className="pl-9" value={search} onChange={(e) => setSearch(e.target.value)} />
      </div>

      {/* Quick Links */}
      <Card>
        <CardHeader className="bg-muted/50 border-b pb-4">
          <CardTitle className="text-lg flex items-center gap-2">
            <Link2 className="h-5 w-5 text-muted-foreground" /> Quick Reference Links
          </CardTitle>
        </CardHeader>
        <CardContent className="p-4 grid sm:grid-cols-2 gap-3">
          {STATIC_LINKS.map((link) => {
            const Icon = link.icon;
            return (
              <a key={link.url} href={link.url} target="_blank" rel="noopener noreferrer"
                className="flex items-start gap-3 p-3 rounded-lg border hover:bg-accent/50 transition-colors group">
                <Icon className="h-5 w-5 text-primary mt-0.5 shrink-0" />
                <div className="min-w-0">
                  <p className="font-medium text-sm group-hover:text-primary transition-colors">{link.title}</p>
                  <p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">{link.description}</p>
                </div>
                <ExternalLink className="h-3.5 w-3.5 text-muted-foreground shrink-0 mt-0.5 opacity-0 group-hover:opacity-100 transition-opacity" />
              </a>
            );
          })}
        </CardContent>
      </Card>

      {/* Dynamic Resources by Category */}
      {categories.length > 0 ? (
        categories.map((cat) => {
          const Icon = CATEGORY_ICONS[cat] || Folder;
          const items = filtered.filter((r) => r.category === cat);
          return (
            <Card key={cat}>
              <CardHeader className="bg-muted/50 border-b pb-4">
                <CardTitle className="text-lg flex items-center gap-2">
                  <Icon className="h-5 w-5 text-muted-foreground" /> {cat}
                  <Badge variant="secondary" className="ml-auto">{items.length}</Badge>
                </CardTitle>
              </CardHeader>
              <CardContent className="p-4 space-y-2">
                {items.map((r) => (
                  <a key={r.id} href={r.url || r.file_url || "#"} target="_blank" rel="noopener noreferrer"
                    className="flex items-center gap-3 p-3 rounded-lg border hover:bg-accent/50 transition-colors group">
                    {r.resource_type === "document" ? (
                      <FileText className="h-5 w-5 text-primary shrink-0" />
                    ) : (
                      <ExternalLink className="h-5 w-5 text-primary shrink-0" />
                    )}
                    <div className="min-w-0 flex-1">
                      <p className="font-medium text-sm group-hover:text-primary transition-colors">{r.title}</p>
                      {r.description && <p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">{r.description}</p>}
                    </div>
                    <Badge variant="outline" className="text-[10px] shrink-0">{r.resource_type}</Badge>
                  </a>
                ))}
              </CardContent>
            </Card>
          );
        })
      ) : (
        filtered.length === 0 && resources.length === 0 && (
          <Card>
            <CardContent className="py-12 text-center text-muted-foreground">
              <BookOpen className="h-10 w-10 mx-auto mb-3 opacity-40" />
              <p className="font-medium">No custom resources yet</p>
              <p className="text-sm mt-1">Your management team can add helpful links and documents here.</p>
            </CardContent>
          </Card>
        )
      )}
    </div>
  );
}
