import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useNavigate } from "react-router-dom";
import { Megaphone, ArrowRight, Pin } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { formatDateTimeShortEST } from "@/lib/timezoneUtils";
import { htmlToPlainText } from "@/lib/htmlTextUtils";

export function AnnouncementsListWidget() {
  const [announcements, setAnnouncements] = useState<any[]>([]);
  const navigate = useNavigate();

  useEffect(() => {
    const nowIso = new Date().toISOString();
    supabase.from("announcements").select("id, title, content, created_at, visibility, pinned, expires_at")
      .eq("status", "active")
      .or(`expires_at.is.null,expires_at.gt.${nowIso}`)
      .order("pinned", { ascending: false })
      .order("created_at", { ascending: false }).limit(5)
      .then(({ data }) => setAnnouncements(data || []));
  }, []);

  return (
    <div className="h-full flex flex-col">
      <div className="px-4 pt-4 pb-2 flex items-center justify-between">
        <div className="flex items-center gap-2 text-[15px] font-semibold">
          <Megaphone className="w-4 h-4 text-primary" /> Announcements
        </div>
        <Badge variant="secondary" className="text-2xs h-5">{announcements.length}</Badge>
      </div>
      <div className="divide-y divide-border flex-1 overflow-auto">
        {announcements.length === 0 ? (
          <p className="p-4 text-[13px] text-muted-foreground text-center">No announcements</p>
        ) : announcements.map((ann) => (
          <div key={ann.id} className="px-4 py-2.5 hover:bg-muted/50 transition-colors cursor-pointer" onClick={() => navigate("/dashboard/announcements")}>
            <div className="flex items-center gap-1.5">
              {ann.pinned && <Pin className="w-3 h-3 text-primary fill-primary shrink-0" />}
              <p className="text-[13px] font-medium text-foreground truncate">{ann.title}</p>
            </div>
            <div className="flex items-center justify-between mt-0.5">
              <p className="text-2xs text-muted-foreground truncate flex-1">{htmlToPlainText(ann.content)}</p>
              <span className="text-2xs text-muted-foreground shrink-0 ml-2">{formatDateTimeShortEST(ann.created_at)}</span>
            </div>
          </div>
        ))}
      </div>
      <Button variant="ghost" className="w-full text-muted-foreground text-[11px] font-semibold h-8 hover:text-primary rounded-t-none border-t" onClick={() => navigate("/dashboard/announcements")}>
        View All <ArrowRight className="w-3 h-3 ml-1" />
      </Button>
    </div>
  );
}
