'use client'

import { useState, useRef, useEffect } from 'react'
import { Trash2, UserPlus, Pencil } from 'lucide-react'
import { toast } from 'sonner'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Badge } from '@/components/ui/badge'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { AddMemberDialog } from './add-member-dialog'

interface JuryMember {
  id: string
  userId: string
  role?: string
  user: {
    id: string
    name: string | null
    email: string
  }
  maxAssignmentsOverride?: number | null
  capModeOverride?: string | null
  preferredStartupRatio?: number | null
}

interface JuryMembersTableProps {
  juryGroupId: string
  members: JuryMember[]
}

function InlineCapEdit({
  memberId,
  currentValue,
  juryGroupId,
}: {
  memberId: string
  currentValue: number | null | undefined
  juryGroupId: string
}) {
  const [editing, setEditing] = useState(false)
  const [value, setValue] = useState(currentValue?.toString() ?? '')
  const inputRef = useRef<HTMLInputElement>(null)
  const utils = trpc.useUtils()

  const { mutate: updateMember, isPending } = trpc.juryGroup.updateMember.useMutation({
    onSuccess: () => {
      utils.juryGroup.getById.invalidate({ id: juryGroupId })
      toast.success('Cap updated')
      setEditing(false)
    },
    onError: (err) => toast.error(err.message),
  })

  useEffect(() => {
    if (editing) inputRef.current?.focus()
  }, [editing])

  const save = () => {
    const trimmed = value.trim()
    const newVal = trimmed === '' ? null : parseInt(trimmed, 10)
    if (newVal !== null && (isNaN(newVal) || newVal < 1)) {
      toast.error('Enter a positive number or leave empty for no cap')
      return
    }
    if (newVal === (currentValue ?? null)) {
      setEditing(false)
      return
    }
    updateMember({ id: memberId, maxAssignmentsOverride: newVal })
  }

  if (editing) {
    return (
      <Input
        ref={inputRef}
        type="number"
        min={1}
        className="h-7 w-20 text-xs"
        value={value}
        placeholder="∞"
        disabled={isPending}
        onChange={(e) => setValue(e.target.value)}
        onBlur={save}
        onKeyDown={(e) => {
          if (e.key === 'Enter') save()
          if (e.key === 'Escape') { setValue(currentValue?.toString() ?? ''); setEditing(false) }
        }}
      />
    )
  }

  return (
    <button
      type="button"
      className="inline-flex items-center gap-1.5 rounded px-1.5 py-0.5 text-sm hover:bg-muted transition-colors group"
      onClick={() => { setValue(currentValue?.toString() ?? ''); setEditing(true) }}
    >
      <span>{currentValue ?? '∞'}</span>
      <Pencil className="h-3 w-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />
    </button>
  )
}

export function JuryMembersTable({ juryGroupId, members }: JuryMembersTableProps) {
  const [addDialogOpen, setAddDialogOpen] = useState(false)
  const [removingMemberId, setRemovingMemberId] = useState<string | null>(null)
  const utils = trpc.useUtils()

  const { mutate: removeMember, isPending: isRemoving } = trpc.juryGroup.removeMember.useMutation({
    onSuccess: () => {
      utils.juryGroup.getById.invalidate({ id: juryGroupId })
      toast.success('Member removed successfully')
      setRemovingMemberId(null)
    },
    onError: (err) => {
      toast.error(err.message)
      setRemovingMemberId(null)
    },
  })

  const handleRemove = (memberId: string) => {
    removeMember({ id: memberId })
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <Button onClick={() => setAddDialogOpen(true)}>
          <UserPlus className="mr-2 h-4 w-4" />
          Add Member
        </Button>
      </div>

      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Name</TableHead>
              <TableHead className="hidden sm:table-cell">Role</TableHead>
              <TableHead>Email</TableHead>
              <TableHead className="hidden sm:table-cell">Max Assignments</TableHead>
              <TableHead className="hidden lg:table-cell">Cap Mode</TableHead>
              <TableHead>Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {members.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-muted-foreground">
                  No members yet. Add members to get started.
                </TableCell>
              </TableRow>
            ) : (
              members.map((member) => (
                <TableRow key={member.id}>
                  <TableCell className="font-medium">
                    {member.user.name || 'Unnamed User'}
                  </TableCell>
                  <TableCell className="hidden sm:table-cell">
                    <Badge variant="outline" className="text-[10px] capitalize">
                      {member.role?.toLowerCase().replace('_', ' ') || 'member'}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {member.user.email}
                  </TableCell>
                  <TableCell className="hidden sm:table-cell">
                    <InlineCapEdit
                      memberId={member.id}
                      currentValue={member.maxAssignmentsOverride}
                      juryGroupId={juryGroupId}
                    />
                  </TableCell>
                  <TableCell className="hidden lg:table-cell">
                    {member.capModeOverride ? (
                      <Badge variant="outline" className="text-[10px]">
                        {member.capModeOverride}
                      </Badge>
                    ) : (
                      <span className="text-muted-foreground text-xs">Group default</span>
                    )}
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setRemovingMemberId(member.id)}
                      disabled={isRemoving}
                    >
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <AddMemberDialog
        juryGroupId={juryGroupId}
        open={addDialogOpen}
        onOpenChange={setAddDialogOpen}
      />

      <AlertDialog open={!!removingMemberId} onOpenChange={() => setRemovingMemberId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Remove Member</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to remove this member from the jury group? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => removingMemberId && handleRemove(removingMemberId)}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Remove
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
