'use client'

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

interface WithdrawButtonProps {
  projectId: string
}

export function WithdrawButton({ projectId }: WithdrawButtonProps) {
  const [open, setOpen] = useState(false)
  const utils = trpc.useUtils()

  const withdraw = trpc.applicant.withdrawFromCompetition.useMutation({
    onSuccess: (data) => {
      toast.success(`Withdrawn from ${data.roundName}`)
      utils.applicant.getMyDashboard.invalidate()
      utils.applicant.getMyCompetitionTimeline.invalidate()
      setOpen(false)
    },
    onError: (error) => {
      toast.error(error.message)
    },
  })

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger asChild>
        <Button variant="outline" size="sm" className="text-destructive hover:text-destructive">
          <LogOut className="h-4 w-4 mr-1.5" />
          Withdraw
        </Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Withdraw from Competition?</AlertDialogTitle>
          <AlertDialogDescription>
            Are you sure you want to withdraw your project from the current round?
            This action is immediate and cannot be undone by you.
            An administrator would need to re-include your project.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction
            onClick={() => withdraw.mutate({ projectId })}
            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            disabled={withdraw.isPending}
          >
            {withdraw.isPending ? 'Withdrawing...' : 'Yes, Withdraw'}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
