import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { ShieldAlert, FileText, Users, DollarSign, BarChart3, Mail, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";

export default function QuickActionsWidget() {
  const navigate = useNavigate();
  const { toast } = useToast();
  const [notifying, setNotifying] = useState(false);

  const actions = [
    { label: "Generate Violation Notice", path: "/dashboard/violations", icon: ShieldAlert },
    { label: "Review ARC Applications", path: "/dashboard/arc-applications", icon: FileText },
    { label: "Add New Homeowner", path: "/dashboard/owner-roster", icon: Users },
    { label: "Run Financial Report", path: "/dashboard/financial-reports", icon: DollarSign },
  ];

  const handleNotifyBoardOfPendingVotes = async () => {
    setNotifying(true);
    try {
      const { data: openVotes, error } = await supabase
        .from("board_votes")
        .select("id, title")
        .eq("status", "open");
      if (error) throw error;
      if (!openVotes || openVotes.length === 0) {
        toast({ title: "No pending votes", description: "There are no open board votes to notify about." });
        return;
      }
      if (!confirm(`Email all board members about ${openVotes.length} pending vote${openVotes.length === 1 ? "" : "s"}?`)) {
        return;
      }
      let totalSent = 0, totalFailed = 0;
      for (const v of openVotes) {
        const { data, error: invErr } = await supabase.functions.invoke("send-board-vote-invites", {
          body: { board_vote_id: v.id, base_url: window.location.origin },
        });
        if (invErr || data?.error) {
          totalFailed += 1;
        } else {
          totalSent += data?.sent ?? 0;
          totalFailed += data?.failed ?? 0;
        }
      }
      toast({
        title: "Board notified",
        description: `Sent ${totalSent} invitation${totalSent === 1 ? "" : "s"}${totalFailed ? `, ${totalFailed} failed` : ""}.`,
      });
    } catch (err: any) {
      toast({ title: "Error", description: err.message || "Failed to notify board", variant: "destructive" });
    } finally {
      setNotifying(false);
    }
  };

  return (
    <div className="h-full flex flex-col">
      <div className="px-4 pt-4 pb-2">
        <div className="flex items-center gap-2 text-[15px] font-semibold">
          <BarChart3 className="h-4 w-4 text-primary" /> Quick Actions
        </div>
        <p className="text-xs text-muted-foreground">Common administrative tasks</p>
      </div>
      <div className="px-4 pb-4 grid grid-cols-1 sm:grid-cols-2 gap-2 flex-1 content-start">
        {actions.map((action) => (
          <Button
            key={action.label}
            variant="outline"
            className="justify-start gap-2 h-9 text-[13px] font-normal hover:bg-primary/5 hover:text-primary hover:border-primary/20 transition-all"
            onClick={() => navigate(action.path)}
          >
            <action.icon className="w-3.5 h-3.5" />
            {action.label}
          </Button>
        ))}
        <Button
          variant="outline"
          disabled={notifying}
          className="justify-start gap-2 h-9 text-[13px] font-normal hover:bg-primary/5 hover:text-primary hover:border-primary/20 transition-all sm:col-span-2"
          onClick={handleNotifyBoardOfPendingVotes}
        >
          {notifying ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Mail className="w-3.5 h-3.5" />}
          {notifying ? "Notifying board…" : "Notify Board of Pending Votes"}
        </Button>
      </div>
    </div>
  );
}
