import { useEffect, useState } from "react";
import { useParams, Link } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Calendar, MapPin, Phone, Mail, Globe, Clock, Loader2, FileText, Download, CalendarDays, ChevronRight, ExternalLink, ChevronLeft, Megaphone, Folder, FolderOpen } from "lucide-react";
import PublicChatWidget from "@/components/public/PublicChatWidget";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { format } from "date-fns";
import { useCallback, useRef } from "react";
import { htmlToPlainText } from "@/lib/htmlTextUtils";
import ContentBlocksRenderer from "@/components/public-content/ContentBlocksRenderer";
import { PublicPageThemeWrapper } from "@/components/public-content/PublicPageTheme";

function HeroCarousel({ heroImages, accent }: { heroImages: string[]; accent: string }) {
  const [current, setCurrent] = useState(0);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const count = heroImages.length;

  const resetTimer = useCallback(() => {
    if (timerRef.current) clearInterval(timerRef.current);
    if (count > 1) {
      timerRef.current = setInterval(() => setCurrent((p) => (p + 1) % count), 5000);
    }
  }, [count]);

  useEffect(() => {
    resetTimer();
    return () => { if (timerRef.current) clearInterval(timerRef.current); };
  }, [resetTimer]);

  if (count === 0) return null;

  const goTo = (i: number) => { setCurrent(i); resetTimer(); };
  const prev = () => goTo((current - 1 + count) % count);
  const next = () => goTo((current + 1) % count);

  return (
    <div className="relative w-full h-[320px] md:h-[420px] overflow-hidden bg-black">
      {heroImages.map((url, i) => (
        <div
          key={i}
          className="absolute inset-0 transition-opacity duration-700 ease-in-out"
          style={{
            opacity: i === current ? 1 : 0,
            background: `url(${url}) center/cover no-repeat`,
          }}
        />
      ))}
      {count > 1 && (
        <>
          <button
            onClick={prev}
            className="absolute left-3 top-1/2 -translate-y-1/2 z-10 bg-black/40 hover:bg-black/60 text-white rounded-full p-2 transition-colors"
            aria-label="Previous slide"
          >
            <ChevronLeft className="h-5 w-5" />
          </button>
          <button
            onClick={next}
            className="absolute right-3 top-1/2 -translate-y-1/2 z-10 bg-black/40 hover:bg-black/60 text-white rounded-full p-2 transition-colors"
            aria-label="Next slide"
          >
            <ChevronRight className="h-5 w-5" />
          </button>
          <div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-10 flex gap-2">
            {heroImages.map((_, i) => (
              <button
                key={i}
                onClick={() => goTo(i)}
                className={`h-2.5 rounded-full transition-all duration-300 ${i === current ? "w-7 bg-white" : "w-2.5 bg-white/50 hover:bg-white/70"}`}
                aria-label={`Go to slide ${i + 1}`}
              />
            ))}
          </div>
        </>
      )}
    </div>
  );
}

interface PublicPageData {
  id: string;
  slug: string;
  is_published: boolean;
  seo_description: string | null;
  welcome_message: string | null;
  cover_image_url: string | null;
  accent_color: string;
  bg_color?: string | null;
  section_bg_color?: string | null;
  text_color?: string | null;
  heading_color?: string | null;
  font_family?: string | null;
  heading_font_family?: string | null;
  footer_bg_color?: string | null;
  footer_text_color?: string | null;
  logo_width: number;
  modules_enabled: { calendar?: boolean; booking?: boolean; documents?: boolean; amenities?: boolean; contact?: boolean; announcements?: boolean };
  booking_config: any;
  associations: {
    id: string;
    name: string;
    logo_url: string | null;
    address: string | null;
    city: string | null;
    state: string | null;
    zip: string | null;
    phone: string | null;
    email: string | null;
    website: string | null;
    contact_email: string | null;
    care_of_address: string | null;
    mailing_address: string | null;
  };
}

export default function CommunityPage() {
  const { slug } = useParams<{ slug: string }>();
  const [page, setPage] = useState<PublicPageData | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [events, setEvents] = useState<any[]>([]);
  const [publicDocs, setPublicDocs] = useState<any[]>([]);
  const [activeDocFolder, setActiveDocFolder] = useState<string>("");
  const [amenities, setAmenities] = useState<any[]>([]);
  const [announcements, setAnnouncements] = useState<any[]>([]);

  useEffect(() => {
    if (!slug) return;
    loadPage();
  }, [slug]);

  const loadPage = async () => {
    const db = supabase as any;
    const { data, error } = await db
      .from("association_public_pages")
      .select("*, associations(id, name, logo_url, address, city, state, zip, phone, email, website, contact_email, care_of_address, mailing_address)")
      .eq("slug", slug)
      .eq("is_published", true)
      .maybeSingle();

    if (error || !data || !data.associations) {
      setNotFound(true);
      setLoading(false);
      return;
    }

    setPage(data);

    const modules = typeof data.modules_enabled === "string" ? JSON.parse(data.modules_enabled) : data.modules_enabled;
    if (modules?.calendar) {
      const now = new Date().toISOString();
      const { data: evts } = await supabase
        .from("calendar_events")
        .select("id, title, description, start_date, end_date, location, event_type, all_day")
        .eq("association_id", data.associations.id)
        .contains("visibility", ["public"])
        .gte("start_date", now)
        .order("start_date")
        .limit(20);
      setEvents(evts || []);
    }

    if (modules?.documents) {
      const { data: docs } = await (supabase as any)
        .from("documents")
        .select("id, title, file_url, file_name, file_size, category, created_at")
        .eq("association_id", data.associations.id)
        .eq("is_public", true)
        .order("created_at", { ascending: false });
      setPublicDocs(docs || []);
    }

    if (modules?.amenities) {
      const { data: amens } = await (supabase as any)
        .from("amenities")
        .select("id, name, description, amenity_type, cover_image_url")
        .eq("association_id", data.associations.id)
        .eq("is_active", true)
        .eq("show_on_public_page", true)
        .neq("amenity_type", "meeting_calendar")
        .order("sort_order");
      setAmenities(amens || []);
    }

    if (modules?.announcements) {
      const { data: anns } = await (supabase as any)
        .from("announcements")
        .select("id, title, content, created_at, pinned")
        .eq("association_id", data.associations.id)
        .eq("status", "active")
        .in("visibility", ["public", "public_only"])
        .order("pinned", { ascending: false })
        .order("created_at", { ascending: false })
        .limit(10);
      setAnnouncements(anns || []);
    }

    setLoading(false);
  };

  // Set SEO page metadata
  useEffect(() => {
    if (!page) return;
    const title = (page as any).page_title || page.associations.name;
    const description = page.seo_description || page.welcome_message || `${page.associations.name} community information and resources.`;
    document.title = title;
    const ogTitle = document.querySelector('meta[property="og:title"]');
    if (ogTitle) ogTitle.setAttribute("content", title);
    const metaDescription = document.querySelector('meta[name="description"]');
    if (metaDescription) metaDescription.setAttribute("content", description);
    const ogDescription = document.querySelector('meta[property="og:description"]');
    if (ogDescription) ogDescription.setAttribute("content", description);
    const twitterDescription = document.querySelector('meta[name="twitter:description"]');
    if (twitterDescription) twitterDescription.setAttribute("content", description);
    return () => { document.title = "Community Cloud | Avria Community Management"; };
  }, [page]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-white">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (notFound || !page) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-white">
        <div className="text-center">
          <h1 className="text-2xl font-bold mb-2">Page Not Found</h1>
          <p className="text-muted-foreground">This community page doesn't exist or isn't published yet.</p>
        </div>
      </div>
    );
  }

  const assoc = page.associations;
  const modules = typeof page.modules_enabled === "string" ? JSON.parse(page.modules_enabled) : page.modules_enabled;
  const accent = page.accent_color || "#2563EB";
  const footerBg = page.footer_bg_color || "#111827";
  const footerText = page.footer_text_color || "#FFFFFF";

  const fullAddress = [assoc.address, assoc.city, assoc.state, assoc.zip].filter(Boolean).join(", ");

  // Build nav items based on enabled modules
  const navItems: { label: string; href: string; external?: boolean }[] = [];
  if (page.welcome_message) navItems.push({ label: "Home", href: "#home" });
  if (modules?.documents) navItems.push({ label: "Documents", href: "#documents" });
  if (modules?.calendar) navItems.push({ label: "Events", href: "#events" });
  if (modules?.amenities && amenities.length > 0) navItems.push({ label: "Amenities", href: "#amenities" });
  if (modules?.announcements && announcements.length > 0) navItems.push({ label: "Announcements", href: "#announcements" });

  // Add custom links
  const rawLinks = Array.isArray((page as any).custom_links) ? (page as any).custom_links : [];
  rawLinks.forEach((link: { label: string; url: string }) => {
    if (link?.label && link?.url) {
      navItems.push({ label: link.label, href: link.url, external: true });
    }
  });

  navItems.push({ label: "Contact Us", href: "#contact" });

  return (
    <PublicPageThemeWrapper theme={page} className="min-h-screen flex flex-col">
      <div className="w-full max-w-6xl mx-auto shadow-sm flex flex-col flex-1" style={{ backgroundColor: "var(--pp-section)" }}>
      {/* Header / Navbar */}
      <header className="sticky top-0 z-50 border-b border-gray-200 shadow-sm" style={{ backgroundColor: "var(--pp-section)" }}>
        <div className="max-w-5xl mx-auto px-6">
          {/* Logo row */}
          <div className="flex items-center justify-center py-4">
            {assoc.logo_url ? (
              <img
                src={assoc.logo_url}
                alt={`${assoc.name} logo`}
                style={{ width: Math.min(page.logo_width || 200, 280), objectFit: "contain" }}
              />
            ) : (
              <h1 className="text-2xl font-bold tracking-tight" style={{ color: accent }}>{assoc.name}</h1>
            )}
          </div>
          {/* Navigation */}
          {navItems.length > 1 && (
            <nav className="flex items-center justify-center gap-1 pb-3 flex-wrap">
              {navItems.map((item) => (
                <a
                  key={item.href}
                  href={item.href}
                  {...(item.external ? { target: "_blank", rel: "noopener noreferrer" } : {})}
                  className="px-4 py-1.5 text-sm font-medium text-gray-600 hover:text-gray-900 transition-colors rounded-md hover:bg-gray-50 flex items-center gap-1"
                >
                  {item.label}
                  {item.external && <ExternalLink className="h-3 w-3" />}
                </a>
              ))}
            </nav>
          )}
        </div>
      </header>

      {/* Scrolling Announcement Banner */}
      {modules?.announcements && announcements.length > 0 && (
        <div id="announcements" className="overflow-hidden whitespace-nowrap border-b border-gray-200" style={{ backgroundColor: accent }}>
          <div className="inline-flex animate-marquee py-2.5">
            {[...announcements, ...announcements].map((ann: any, i: number) => (
              <span key={`${ann.id}-${i}`} className="inline-flex items-center mx-8 text-sm text-white font-medium">
                <Megaphone className="h-3.5 w-3.5 mr-2 shrink-0" />
                <span className="font-semibold mr-1.5">{ann.title}</span>
                <span className="opacity-80">— {htmlToPlainText(ann.content).slice(0, 120)}{htmlToPlainText(ann.content).length > 120 ? '…' : ''}</span>
              </span>
            ))}
          </div>
        </div>
      )}

      {/* Hero Banner / Carousel */}
      <HeroCarousel
        heroImages={(() => {
          const raw = (page as any).hero_images;
          const imgs = Array.isArray(raw) ? raw.filter((u: string) => typeof u === "string" && u.trim()) : [];
          return imgs.length > 0 ? imgs : page.cover_image_url ? [page.cover_image_url] : [];
        })()}
        accent={accent}
      />

      {/* Main Content */}
      <main className="flex-1">
        <div className="max-w-5xl mx-auto px-6 py-12 w-full">
          {(() => {
            const sidebarEnabled = Boolean((page as any).sidebar_enabled);
            const sidebarBlocks = (page as any).sidebar_blocks;
            const bodyBlocks = (page as any).body_blocks;
            const sidebarTitle = (page as any).sidebar_title || "Information";
            return (
              <div className={sidebarEnabled ? "grid gap-10 lg:grid-cols-[1fr_300px]" : ""}>
                <div className="space-y-14 min-w-0">
                  {/* Welcome Section */}
                  {page.welcome_message && (
                    <section id="home">
                      <h2 className="text-2xl font-bold tracking-tight mb-4" style={{ color: accent }}>Welcome</h2>
                      <p className="text-gray-700 text-base leading-relaxed whitespace-pre-wrap max-w-3xl">
                        {page.welcome_message}
                      </p>
                    </section>
                  )}

                  {/* Custom Body Blocks */}
                  {Array.isArray(bodyBlocks) && bodyBlocks.length > 0 && (
                    <section id="custom-content" className="max-w-3xl">
                      <ContentBlocksRenderer blocks={bodyBlocks} accent={accent} variant="main" />
                    </section>
                  )}

          {/* Documents Section */}
          {modules?.documents && (
            <section id="documents">
              <h2 className="text-xl font-bold tracking-tight mb-5 flex items-center gap-2" style={{ color: accent }}>
                <FileText className="h-5 w-5" /> Documents
              </h2>
              {publicDocs.length === 0 ? (
                <p className="text-gray-500 text-sm">No public documents available.</p>
              ) : (() => {
                const folders = Array.from(new Set(publicDocs.map((d: any) => d.category || "General"))).sort() as string[];
                const currentFolder = activeDocFolder || folders[0];
                const filteredDocs = publicDocs.filter((d: any) => (d.category || "General") === currentFolder);
                return (
                  <div>
                    <div className="flex flex-wrap gap-2 mb-4">
                      {folders.map((folder: string) => {
                        const count = publicDocs.filter((d: any) => (d.category || "General") === folder).length;
                        const isActive = folder === currentFolder;
                        return (
                          <button
                            key={folder}
                            onClick={() => setActiveDocFolder(folder)}
                            className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all border ${
                              isActive
                                ? "text-white shadow-sm"
                                : "bg-white text-gray-700 border-gray-200 hover:bg-gray-50"
                            }`}
                            style={isActive ? { backgroundColor: accent, borderColor: accent } : undefined}
                          >
                            {isActive ? <FolderOpen className="h-4 w-4" /> : <Folder className="h-4 w-4" />}
                            <span className="capitalize">{folder}</span>
                            <span className={`text-xs px-1.5 py-0.5 rounded-full ${isActive ? "bg-white/20" : "bg-gray-100 text-gray-500"}`}>{count}</span>
                          </button>
                        );
                      })}
                    </div>
                    <div className="grid gap-2">
                      {filteredDocs.map((doc: any) => (
                        <div key={doc.id} className="flex items-center justify-between p-4 rounded-lg border border-gray-200 bg-white hover:bg-gray-50 transition-colors">
                          <div className="flex items-center gap-3 min-w-0">
                            <div className="p-2 rounded-md bg-gray-100">
                              <FileText className="h-4 w-4 text-gray-500" />
                            </div>
                            <div className="min-w-0">
                              <p className="font-medium text-sm text-gray-900 truncate">{doc.title}</p>
                            </div>
                          </div>
                          {doc.file_url && (
                            <a
                              href={doc.file_url}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="shrink-0 flex items-center gap-1.5 text-xs font-semibold px-4 py-2 rounded-md border border-gray-300 text-gray-700 hover:bg-gray-100 transition-colors"
                            >
                              <Download className="h-3.5 w-3.5" /> Download
                            </a>
                          )}
                        </div>
                      ))}
                    </div>
                  </div>
                );
              })()}
            </section>
          )}

          {/* Calendar Section */}
          {modules?.calendar && (
            <section id="events">
              <h2 className="text-xl font-bold tracking-tight mb-5 flex items-center gap-2" style={{ color: accent }}>
                <Calendar className="h-5 w-5" /> Upcoming Events
              </h2>
              {events.length === 0 ? (
                <p className="text-gray-500 text-sm">No upcoming events.</p>
              ) : (
                <div className="grid gap-3">
                  {events.map((evt) => (
                    <div key={evt.id} className="flex gap-4 p-4 rounded-lg border border-gray-200 bg-white">
                      <div
                        className="flex flex-col items-center justify-center rounded-lg px-3 py-2 text-white text-xs font-bold min-w-[56px] shadow-sm"
                        style={{ backgroundColor: accent }}
                      >
                        <span className="uppercase text-[10px] tracking-wider">{format(new Date(evt.start_date), "MMM")}</span>
                        <span className="text-xl leading-tight">{format(new Date(evt.start_date), "d")}</span>
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="font-semibold text-sm text-gray-900">{evt.title}</p>
                        <p className="text-xs text-gray-500 flex items-center gap-1 mt-1">
                          <Clock className="h-3 w-3" />
                          {evt.all_day
                            ? "All Day"
                            : format(new Date(evt.start_date), "h:mm a")}
                          {evt.end_date && !evt.all_day && ` – ${format(new Date(evt.end_date), "h:mm a")}`}
                        </p>
                        {evt.location && (
                          <p className="text-xs text-gray-500 flex items-center gap-1 mt-0.5">
                            <MapPin className="h-3 w-3" /> {evt.location}
                          </p>
                        )}
                        {evt.description && (
                          <p className="text-xs text-gray-500 mt-1.5 line-clamp-2">{evt.description}</p>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </section>
          )}


          {/* Amenities Section */}
          {modules?.amenities && amenities.length > 0 && (
            <section id="amenities">
              <h2 className="text-xl font-bold tracking-tight mb-5" style={{ color: accent }}>Amenities</h2>
              <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
                {amenities.map(a => {
                  const typeIcon = a.amenity_type === "map" ? MapPin
                    : ["booking", "rental_calendar"].includes(a.amenity_type) ? CalendarDays
                    : FileText;
                  const Icon = typeIcon;
                  return (
                    <Link key={a.id} to={`/community/${slug}/amenities/${a.id}`} className="group block">
                      <div className="rounded-xl border border-gray-200 overflow-hidden bg-white hover:shadow-lg transition-all duration-200">
                        {a.cover_image_url ? (
                          <div className="h-40 w-full" style={{ background: `url(${a.cover_image_url}) center/cover no-repeat` }} />
                        ) : (
                          <div className="h-28 w-full flex items-center justify-center" style={{ backgroundColor: `${accent}08` }}>
                            <Icon className="h-10 w-10" style={{ color: `${accent}40` }} />
                          </div>
                        )}
                        <div className="p-4">
                          <p className="font-semibold text-sm text-gray-900 group-hover:text-gray-700">{a.name}</p>
                          {a.description && <p className="text-xs text-gray-500 mt-1 line-clamp-2">{a.description}</p>}
                          <p className="text-xs font-medium mt-3 flex items-center gap-1" style={{ color: accent }}>
                            View Details <ChevronRight className="h-3 w-3" />
                          </p>
                        </div>
                      </div>
                    </Link>
                  );
                })}
              </div>
            </section>
          )}
                </div>

                {sidebarEnabled && Array.isArray(sidebarBlocks) && sidebarBlocks.length > 0 && (
                  <aside className="space-y-4 lg:sticky lg:top-6 lg:self-start">
                    <div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
                      {sidebarTitle && (
                        <h3 className="text-base font-bold tracking-tight mb-3" style={{ color: accent }}>
                          {sidebarTitle}
                        </h3>
                      )}
                      <ContentBlocksRenderer blocks={sidebarBlocks} accent={accent} variant="sidebar" />
                    </div>
                  </aside>
                )}
              </div>
            );
          })()}
        </div>
      </main>

      {/* Professional Footer */}
      <footer id="contact" style={{ backgroundColor: footerBg, color: footerText }}>
        <div className="max-w-5xl mx-auto px-6 py-14">
          {/* Footer heading */}
          <div className="text-center mb-10">
            <h2 className="text-2xl md:text-3xl font-bold">Connect with {assoc.name.split(' ')[0]}</h2>
          </div>

          {/* 3-column footer grid */}
          <div className="grid md:grid-cols-3 gap-10 md:gap-8">
            {/* Column 1: Association Info */}
            <div>
              <h3 className="font-bold text-lg mb-4">{assoc.name}</h3>
              <div className="text-sm space-y-1.5 leading-relaxed" style={{ opacity: 0.7 }}>
                {assoc.care_of_address && <p>c/o {assoc.care_of_address}</p>}
                {assoc.mailing_address && assoc.mailing_address.split('\n').map((line, i) => (
                  <p key={i}>{line.trim()}</p>
                ))}
              </div>
            </div>

            {/* Column 2: Contact Us */}
            <div>
              <h3 className="font-bold text-lg mb-4">Contact Us</h3>
              <div className="space-y-3 text-sm">
                {assoc.phone && (
                  <a href={`tel:${assoc.phone}`} className="flex items-center gap-2.5 transition-colors" style={{ opacity: 0.8 }}>
                    <Phone className="h-4 w-4 shrink-0" style={{ color: accent }} />
                    {assoc.phone}
                  </a>
                )}
                {(assoc.contact_email || assoc.email) && (
                  <a href={`mailto:${assoc.contact_email || assoc.email}`} className="flex items-center gap-2.5 transition-colors" style={{ opacity: 0.8 }}>
                    <Mail className="h-4 w-4 shrink-0" style={{ color: accent }} />
                    {assoc.contact_email || assoc.email}
                  </a>
                )}
                {assoc.website && (
                  <a href={assoc.website} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2.5 transition-colors" style={{ opacity: 0.8 }}>
                    <Globe className="h-4 w-4 shrink-0" style={{ color: accent }} />
                    {assoc.website}
                  </a>
                )}
              </div>
            </div>

            {/* Column 3: Information / Map */}
            <div>
              <h3 className="font-bold text-lg mb-4">Information</h3>
              {fullAddress && (
                <div>
                  <a
                    href={`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(fullAddress)}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1.5 text-sm font-medium mb-3 hover:underline"
                    style={{ color: accent }}
                  >
                    Open in Maps <ExternalLink className="h-3.5 w-3.5" />
                  </a>
                  <div className="rounded-lg overflow-hidden border border-gray-700">
                    <iframe
                      title="Association Location"
                      width="100%"
                      height="180"
                      style={{ border: 0 }}
                      loading="lazy"
                      referrerPolicy="no-referrer-when-downgrade"
                      src={`https://www.google.com/maps/embed/v1/place?key=AIzaSyBFw0Qbyq9zTFTd-tUY6dZWTgaQzuU17R8&q=${encodeURIComponent(fullAddress)}&maptype=satellite`}
                    />
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Copyright bar */}
        <div className="border-t" style={{ borderColor: 'rgba(128,128,128,0.3)' }}>
          <div className="max-w-5xl mx-auto px-6 py-5 text-center">
            <p className="text-xs" style={{ opacity: 0.5 }}>
              © {new Date().getFullYear()} {assoc.name} | <a href="https://avria.cloud" className="hover:opacity-80 transition-opacity" target="_blank" rel="noopener noreferrer">Avria Community Management LLC</a>
              <span className="mx-2">|</span>
              <a href="/privacy" target="_blank" rel="noopener noreferrer" className="hover:opacity-80 transition-opacity">Privacy Policy</a>
              <span className="mx-2">|</span>
              <a href="/terms" target="_blank" rel="noopener noreferrer" className="hover:opacity-80 transition-opacity">Terms of Service</a>
            </p>
          </div>
        </div>
      </footer>

      <PublicChatWidget associationId={assoc.id} accentColor={accent} />
      </div>
    </PublicPageThemeWrapper>
  );
}
