import type { ControllerFieldState } from 'react-hook-form'
import { XIcon, CheckIcon, AlertTriangleIcon, UserIcon } from 'lucide-react'
import { formatCPF } from '@brazilian-utils/brazilian-utils'

import { cn, initials } from '@repo/ui/lib/utils'
import { Avatar, AvatarFallback } from '@repo/ui/components/ui/avatar'
import { Abbr } from '@repo/ui/components/abbr'
import { Spinner } from '@repo/ui/components/ui/spinner'
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupInput
} from '@repo/ui/components/ui/input-group'
import { CommandItem } from '@repo/ui/components/ui/command'
import { SearchFilter } from '@repo/ui/components/search-filter'

import type { User } from './data'

interface UserPickerProps {
  value?: User
  onChange: (value: User | null) => void
  onSearch: (search: string) => Promise<User[]>
  fieldState: ControllerFieldState
}

export function UserPicker({
  value,
  onChange,
  onSearch,
  fieldState
}: UserPickerProps) {
  return (
    <SearchFilter
      align="start"
      onChange={onChange}
      onSearch={onSearch}
      render={({ id, name, email, cpf, onSelect, onClose }) => (
        <CommandItem
          key={id}
          value={id}
          className="cursor-pointer"
          disabled={!cpf}
          onSelect={() => {
            onSelect()
            onClose()
          }}
        >
          <div className="flex gap-2.5 items-start">
            <Avatar className="size-10 hidden lg:block">
              <AvatarFallback className="border">
                {initials(name)}
              </AvatarFallback>
            </Avatar>

            <ul>
              <li className="font-bold">
                <Abbr>{name}</Abbr>
              </li>
              <li className="text-muted-foreground text-sm">
                <Abbr>{email}</Abbr>
              </li>

              {cpf ? (
                <li className="text-muted-foreground text-sm">
                  {formatCPF(cpf)}
                </li>
              ) : (
                <li className="flex gap-1 items-center text-red-400">
                  <AlertTriangleIcon className="text-red-400" />
                  Inelegível
                </li>
              )}
            </ul>
          </div>

          <CheckIcon
            className={cn(
              'ml-auto',
              value?.id === id ? 'opacity-100' : 'opacity-0'
            )}
          />
        </CommandItem>
      )}
    >
      {({ loading }) => (
        <InputGroup>
          <InputGroupInput
            readOnly
            value={value?.name || ''}
            autoFocus={true}
            placeholder="Colaborador"
            className="cursor-pointer"
            autoComplete="off"
            aria-invalid={!!fieldState.error}
          />
          <InputGroupAddon>
            <UserIcon />
          </InputGroupAddon>

          {value && (
            <InputGroupAddon align="inline-end" className="mr-0">
              <InputGroupButton
                variant="ghost"
                tabIndex={-1}
                size="icon-xs"
                className="cursor-pointer"
                onClick={(e) => {
                  e.preventDefault()
                  onChange?.(null)
                }}
              >
                <XIcon />
              </InputGroupButton>
            </InputGroupAddon>
          )}

          {loading && (
            <InputGroupAddon align="inline-end">
              <Spinner />
            </InputGroupAddon>
          )}
        </InputGroup>
      )}
    </SearchFilter>
  )
}
