"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Send } from "lucide-react";
import { toast } from "sonner";
import { apiRequest } from "@/lib/storeHelper"; // ✅ API helper

// ✅ Define props type
interface BroadcastDialogProps {
  open: boolean;
  setOpen: (open: boolean) => void;
}

export default function BroadcastDialog({ open, setOpen }: BroadcastDialogProps) {
  const [broadcastMessage, setBroadcastMessage] = useState<string>("");
  const [sendingBroadcast, setSendingBroadcast] = useState<boolean>(false);

  // ✅ Send Broadcast Message
  const sendBroadcast = async () => {
    if (!broadcastMessage.trim()) {
      toast.warning("Broadcast message cannot be empty.");
      return;
    }

    try {
      setSendingBroadcast(true);

      // ✅ API Call
      const response = await apiRequest("/storefront/broadcast", "POST", { message: broadcastMessage });

      if (response.error) {
        throw new Error(response.error);
      }

      toast.success(`Broadcast sent to ${response.totalUsers} users!`);
      setBroadcastMessage("");
      setOpen(false);
    } catch (error) {
      toast.error("Failed to send broadcast message.");
    } finally {
      setSendingBroadcast(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent>
        <DialogHeader>
          <Send className="h-6 w-6 text-emerald-600" />
          <DialogTitle>Global Broadcast Message</DialogTitle>
        </DialogHeader>
        <Textarea
          placeholder="Type your message here..."
          value={broadcastMessage}
          onChange={(e) => setBroadcastMessage(e.target.value)}
        />
        <DialogFooter>
          <Button onClick={() => setOpen(false)} variant="secondary">
            Cancel
          </Button>
          <Button onClick={sendBroadcast} disabled={sendingBroadcast} className="bg-emerald-600 hover:bg-emerald-700">
            {sendingBroadcast ? "Sending..." : "Send Broadcast"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}