import { useCallback, useState } from "react";
import { Check, Copy, Link, Loader2, UserPlus } from "lucide-react";
import { api } from "@/client";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";

type Props = {
  workspaceId: string;
  roomId?: string;
  children: React.ReactNode;
};

export default function InviteDialog({ workspaceId, roomId, children }: Props) {
  const [open, setOpen] = useState(false);
  const [inviteLink, setInviteLink] = useState("");
  const [generating, setGenerating] = useState(false);
  const [copied, setCopied] = useState(false);
  const { toast } = useToast();

  const handleGenerate = useCallback(async () => {
    setGenerating(true);
    try {
      const res = await api.post<{ data?: { code: string } }>(
        "/api/v1/ws/invites",
        {
          workspace: workspaceId,
          room: roomId ?? null,
        },
      );
      const code = res.data?.data?.code;
      if (code) {
        const link = `${window.location.origin}/join/${code}`;
        setInviteLink(link);
        await navigator.clipboard.writeText(link);
        setCopied(true);
        toast({
          title: "Invite link copied",
          description: "Share this link with your team",
        });
        setTimeout(() => setCopied(false), 2000);
      }
    } catch {
      toast({
        title: "Error",
        description: "Failed to create invite",
        variant: "destructive",
      });
    } finally {
      setGenerating(false);
    }
  }, [workspaceId, roomId, toast]);

  const handleCopy = useCallback(async () => {
    if (!inviteLink) return;
    await navigator.clipboard.writeText(inviteLink);
    setCopied(true);
    toast({ title: "Copied!" });
    setTimeout(() => setCopied(false), 2000);
  }, [inviteLink, toast]);

  return (
    <Dialog onOpenChange={setOpen} open={open}>
      <DialogTrigger>{children}</DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-base">
            <UserPlus className="size-5 text-primary/60" />
            Invite People
          </DialogTitle>
          <DialogDescription>
            Generate an invite link to share with your team.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-2">
            <Label className="text-[13px]" htmlFor="invite-link">
              Invite link
            </Label>
            {inviteLink ? (
              <div className="flex items-center gap-2">
                <Input
                  className="flex-1 font-mono text-[12px]"
                  id="invite-link"
                  readOnly
                  value={inviteLink}
                />
                <Button
                  className="shrink-0 cursor-pointer"
                  onClick={handleCopy}
                  size="icon"
                  variant="outline"
                >
                  {copied ? (
                    <Check className="size-4 text-emerald-500" />
                  ) : (
                    <Copy className="size-4" />
                  )}
                </Button>
              </div>
            ) : (
              <div className="flex items-center gap-3 rounded-lg border border-dashed border-border/40 px-4 py-7">
                <Link className="size-5 shrink-0 text-muted-foreground/30" />
                <p className="text-sm text-muted-foreground/50">
                  Click generate to create an invite link.
                </p>
              </div>
            )}
          </div>
        </div>

        <DialogFooter>
          <Button
            className="cursor-pointer"
            onClick={() => setOpen(false)}
            variant="outline"
          >
            Close
          </Button>
          <Button
            className="cursor-pointer"
            disabled={generating}
            onClick={handleGenerate}
          >
            {generating && (
              <Loader2 className="mr-2 size-4 animate-spin" />
            )}
            Generate Invite
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
