'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 { Send, Loader2 } from 'lucide-react'

export type SendRemindersButtonProps = {
  roundId: string
}

export function SendRemindersButton({ roundId }: SendRemindersButtonProps) {
  const [open, setOpen] = useState(false)
  const mutation = trpc.evaluation.triggerReminders.useMutation({
    onSuccess: (data) => {
      toast.success(`Sent ${data.sent} reminder(s)`)
      setOpen(false)
    },
    onError: (err) => toast.error(err.message),
  })

  return (
    <>
      <Button variant="outline" size="sm" onClick={() => setOpen(true)}>
        <Send className="h-4 w-4 mr-1.5" />
        Send Reminders
      </Button>
      <AlertDialog open={open} onOpenChange={setOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Send evaluation reminders?</AlertDialogTitle>
            <AlertDialogDescription>
              This will send reminder emails to all jurors who have incomplete evaluations for this round.
            </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" />}
              Send Reminders
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}
