"use client"

import { Share2, Copy, Check } from "lucide-react"
import { useState } from "react"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"

type ShareButtonProps = {
  bookId: string
  title: string
}

export default function ShareButton({ bookId, title }: ShareButtonProps) {
  const [copied, setCopied] = useState(false)
  const url = `${process.env.NEXT_PUBLIC_APP_URL}/books/${bookId}`

  async function handleCopy() {
    await navigator.clipboard.writeText(url)
    setCopied(true)
    toast.success("Link copied to clipboard")
    setTimeout(() => setCopied(false), 2000)
  }

  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button variant="ghost" size="sm" type="button" className="h-7 px-2 text-xs">
          <Share2 className="size-3 mr-1" />
          Share
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Share this book</DialogTitle>
        </DialogHeader>
        <p className="text-sm text-muted-foreground line-clamp-1">{title}</p>
        <div className="flex items-center gap-2 mt-2">
          <div className="flex-1 px-3 py-2 rounded-lg bg-muted text-sm font-mono truncate text-muted-foreground">
            {url}
          </div>
          <Button
            type="button"
            size="icon"
            onClick={handleCopy}
            className="shrink-0"
          >
            {copied
              ? <Check className="size-4" />
              : <Copy className="size-4" />
            }
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  )
}