'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog'
import { Loader2, UserMinus } from 'lucide-react'
import { toast } from 'sonner'

const MIN_REASON = 10
const MAX_REASON = 1000

export function DropAssignmentDialog({
  assignmentId,
  projectTitle,
}: {
  assignmentId: string
  projectTitle: string
}) {
  const router = useRouter()
  const [open, setOpen] = useState(false)
  const [reason, setReason] = useState('')

  const drop = trpc.mentor.dropAssignment.useMutation({
    onSuccess: () => {
      toast.success('You have dropped this assignment.')
      setOpen(false)
      router.push('/mentor')
      router.refresh()
    },
    onError: (e) => {
      toast.error(e.message)
    },
  })

  const trimmed = reason.trim()
  const tooShort = trimmed.length < MIN_REASON
  const tooLong = trimmed.length > MAX_REASON

  return (
    <AlertDialog
      open={open}
      onOpenChange={(next) => {
        if (!drop.isPending) setOpen(next)
        if (!next) setReason('')
      }}
    >
      <AlertDialogTrigger asChild>
        <Button variant="outline" size="sm" className="text-destructive hover:text-destructive">
          <UserMinus className="mr-2 h-4 w-4" />
          Drop this team
        </Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Drop {projectTitle}?</AlertDialogTitle>
          <AlertDialogDescription>
            The team will be unassigned from you and an admin will be notified so they can find a
            replacement mentor. Please share why so we can adjust future assignments.
          </AlertDialogDescription>
        </AlertDialogHeader>

        <div className="space-y-2">
          <Label htmlFor="drop-reason">Reason</Label>
          <Textarea
            id="drop-reason"
            value={reason}
            onChange={(e) => setReason(e.target.value)}
            placeholder="e.g. schedule conflict, expertise mismatch, conflict of interest..."
            rows={4}
            disabled={drop.isPending}
            className="resize-none"
          />
          <p
            className={`text-xs ${tooShort || tooLong ? 'text-destructive' : 'text-muted-foreground'}`}
          >
            {trimmed.length}/{MAX_REASON} characters · minimum {MIN_REASON}
          </p>
        </div>

        <AlertDialogFooter>
          <AlertDialogCancel disabled={drop.isPending}>Cancel</AlertDialogCancel>
          <AlertDialogAction
            disabled={tooShort || tooLong || drop.isPending}
            onClick={(e) => {
              e.preventDefault()
              drop.mutate({ assignmentId, reason: trimmed })
            }}
            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            {drop.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Drop assignment
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
