"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";

interface BroadcastDialogProps {
  open: boolean;
  setOpen: (open: boolean) => void;
}

export default function BroadcastDialog({ open, setOpen }: BroadcastDialogProps) {
  const [broadcastMessage, setBroadcastMessage] = useState("");
  const [isSending, setIsSending] = useState(false);

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

    try {
      setIsSending(true);
      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 {
      setIsSending(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 variant="secondary" onClick={() => setOpen(false)}>
            Cancel
          </Button>
          <Button 
            onClick={sendBroadcast} 
            disabled={isSending}
            className="bg-emerald-600 hover:bg-emerald-700"
          >
            {isSending ? "Sending..." : "Send Broadcast"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}