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

interface BroadcastMessage {
  message: string;
}

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);
      await apiRequest("/storefront/broadcast", "POST", { message: broadcastMessage });
      toast.success("Broadcast message sent successfully!");
      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 value={broadcastMessage} onChange={(e) => setBroadcastMessage(e.target.value)} />
        <DialogFooter>
          <Button onClick={() => setOpen(false)}>Cancel</Button>
          <Button onClick={sendBroadcast} disabled={sendingBroadcast}>
            {sendingBroadcast ? "Sending..." : "Send Broadcast"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
