import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { toast } from "sonner";
import { Clock, UserPlus } from "lucide-react";

const csrfToken = () => (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

interface WaitlistButtonProps {
  courseId: string;
  courseTitle: string;
  startDate?: string;
}

const WaitlistButton = ({ courseId, courseTitle, startDate }: WaitlistButtonProps) => {
  const { user } = useAuth();
  const queryClient = useQueryClient();
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({
    contact_name: "",
    contact_email: user?.email || "",
    contact_phone: "",
    num_delegates: 1,
  });

  const joinMutation = useMutation({
    mutationFn: async () => {
      const res = await fetch("/api/marketplace/course-waitlist", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": csrfToken(),
        },
        body: JSON.stringify({
          course_id: courseId,
          start_date: startDate || new Date().toISOString().split("T")[0],
          user_id: user?.id || null,
          contact_name: form.contact_name,
          contact_email: form.contact_email,
          contact_phone: form.contact_phone || null,
          num_delegates: form.num_delegates,
        }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.message || "Failed to join waitlist");
      }
    },
    onSuccess: () => {
      toast.success("You've been added to the waitlist! We'll notify you when a spot opens.");
      setOpen(false);
      queryClient.invalidateQueries({ queryKey: ["waitlist"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="heroOutline" size="lg" className="w-full">
          <Clock className="h-4 w-4 mr-2" /> Join Waitlist
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <UserPlus className="h-5 w-5 text-primary" />
            Join Waitlist — {courseTitle}
          </DialogTitle>
        </DialogHeader>
        <div className="space-y-4 mt-4">
          <p className="text-sm text-muted-foreground">
            This course is currently full. Enter your details and we'll notify you as soon as a place becomes available.
          </p>
          <div>
            <Label>Full Name *</Label>
            <Input
              value={form.contact_name}
              onChange={(e) => setForm({ ...form, contact_name: e.target.value })}
              placeholder="Your full name"
            />
          </div>
          <div>
            <Label>Email *</Label>
            <Input
              type="email"
              value={form.contact_email}
              onChange={(e) => setForm({ ...form, contact_email: e.target.value })}
              placeholder="your@email.com"
            />
          </div>
          <div>
            <Label>Phone</Label>
            <Input
              value={form.contact_phone}
              onChange={(e) => setForm({ ...form, contact_phone: e.target.value })}
              placeholder="Optional"
            />
          </div>
          <div>
            <Label>Number of Delegates</Label>
            <Input
              type="number"
              min={1}
              max={20}
              value={form.num_delegates}
              onChange={(e) => setForm({ ...form, num_delegates: parseInt(e.target.value) || 1 })}
            />
          </div>
          <Button
            variant="hero"
            className="w-full"
            disabled={!form.contact_name || !form.contact_email || joinMutation.isPending}
            onClick={() => joinMutation.mutate()}
          >
            {joinMutation.isPending ? "Joining..." : "Join Waitlist"}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default WaitlistButton;
