'use client'

import { useState } from 'react'
import { trpc } from '@/lib/trpc/client'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Mail, Loader2 } from 'lucide-react'

export type NotifyJurorsButtonProps = {
  roundId: string
}

export function NotifyJurorsButton({ roundId }: NotifyJurorsButtonProps) {
  const [open, setOpen] = useState(false)
  const mutation = trpc.assignment.notifyJurorsOfAssignments.useMutation({
    onSuccess: (data) => {
      toast.success(`Notified ${data.jurorCount} juror(s) of their assignments`)
      setOpen(false)
    },
    onError: (err) => toast.error(err.message),
  })

  return (
    <>
      <Button variant="outline" size="sm" onClick={() => setOpen(true)}>
        <Mail className="h-4 w-4 mr-1.5" />
        Notify Jurors
      </Button>
      <AlertDialog open={open} onOpenChange={setOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Notify jurors of their assignments?</AlertDialogTitle>
            <AlertDialogDescription>
              This will send an email to every juror assigned to this round, reminding them of how many projects they need to evaluate.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => mutation.mutate({ roundId })}
              disabled={mutation.isPending}
            >
              {mutation.isPending && <Loader2 className="h-4 w-4 mr-1.5 animate-spin" />}
              Notify Jurors
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}
