'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Switch } from '@/components/ui/switch'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Loader2 } from 'lucide-react'

export type AttendeeSelection = {
  attendingUserIds: string[]
  visaFlags: Record<string, boolean>
}

type Member = {
  userId: string
  name: string | null
  role: string
  email: string
}

interface Props {
  open: boolean
  onOpenChange: (open: boolean) => void
  members: Member[]
  cap: number
  onConfirm: (attendingUserIds: string[], visaFlags: Record<string, boolean>) => void
  initial?: AttendeeSelection
  isPending?: boolean
}

export function EnrollAttendeesDialog({
  open,
  onOpenChange,
  members,
  cap,
  onConfirm,
  initial,
  isPending = false,
}: Props) {
  const [selected, setSelected] = useState<Set<string>>(new Set())
  const [visa, setVisa] = useState<Record<string, boolean>>({})

  // Seed from initial or default to first member (the lead)
  useEffect(() => {
    if (!open) return
    if (initial) {
      setSelected(new Set(initial.attendingUserIds))
      setVisa(initial.visaFlags)
    } else {
      const defaultSelected = members.slice(0, 1).map((m) => m.userId)
      setSelected(new Set(defaultSelected))
      setVisa({})
    }
  }, [open, initial, members])

  const overCap = selected.size > cap
  const noneSelected = selected.size === 0

  const toggleMember = (userId: string, checked: boolean) => {
    setSelected((prev) => {
      const next = new Set(prev)
      if (checked) next.add(userId)
      else next.delete(userId)
      return next
    })
  }

  const handleConfirm = () => {
    const ids = Array.from(selected)
    onConfirm(
      ids,
      Object.fromEntries(ids.map((id) => [id, !!visa[id]])),
    )
  }

  return (
    <Dialog
      open={open}
      onOpenChange={(next) => {
        if (!isPending) onOpenChange(next)
      }}
    >
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Select attendees</DialogTitle>
          <DialogDescription>
            Choose up to {cap} team member{cap === 1 ? '' : 's'} who will attend. Toggle
            &quot;Visa?&quot; for anyone who needs a visa letter.
          </DialogDescription>
        </DialogHeader>

        <ul className="max-h-[50vh] space-y-2 overflow-y-auto pr-1">
          {members.map((m) => {
            const checked = selected.has(m.userId)
            const atCap = !checked && selected.size >= cap
            return (
              <li
                key={m.userId}
                className="flex items-start justify-between gap-4 rounded-md border px-3 py-2"
              >
                <label className="flex flex-1 cursor-pointer items-start gap-3">
                  <Checkbox
                    checked={checked}
                    disabled={atCap}
                    onCheckedChange={(c) => toggleMember(m.userId, c === true)}
                    className="mt-0.5"
                  />
                  <div>
                    <div className="text-sm font-medium">{m.name ?? m.email}</div>
                    <div className="text-muted-foreground text-xs">
                      {m.email}
                      {m.role && m.role !== 'MEMBER' ? ` · ${m.role.toLowerCase()}` : ''}
                    </div>
                  </div>
                </label>
                {checked && (
                  <label className="flex items-center gap-2 text-xs">
                    <span className="text-muted-foreground">Visa?</span>
                    <Switch
                      checked={!!visa[m.userId]}
                      onCheckedChange={(c) => setVisa((prev) => ({ ...prev, [m.userId]: c }))}
                    />
                  </label>
                )}
              </li>
            )
          })}
        </ul>

        {overCap && (
          <p className="text-destructive text-sm">
            Please select no more than {cap} member{cap === 1 ? '' : 's'}.
          </p>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isPending}>
            Cancel
          </Button>
          <Button
            onClick={handleConfirm}
            disabled={overCap || noneSelected || isPending}
          >
            {isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Confirm attendees
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
