// frontend/src/components/tickets/TicketFilterBar.tsx
import { useState } from 'react'
import { Search, X, User } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { TicketFilters, PSAPriority } from '@/types/tickets'
import type { PSABoard, PSATicketStatusItem } from '@/types/integrations'

interface TicketFilterBarProps {
  filters: TicketFilters
  onChange: (updated: Partial<TicketFilters>) => void
  boards: PSABoard[]
  statuses: PSATicketStatusItem[]
  priorities: PSAPriority[]
  members: { id: number; name: string }[]
  total: number
  page: number
  pageSize: number
  onPageChange: (page: number) => void
  loading: boolean
}

export function TicketFilterBar({
  filters, onChange, boards, statuses, priorities, members,
  total, page, pageSize, onPageChange, loading,
}: TicketFilterBarProps) {
  const start = (page - 1) * pageSize + 1
  const end = Math.min(page * pageSize, total)
  const hasNext = page * pageSize < total
  const hasPrev = page > 1

  // Member search state — text filter over the member list
  const [memberSearch, setMemberSearch] = useState('')
  const [memberDropdownOpen, setMemberDropdownOpen] = useState(false)

  const currentMemberName = typeof filters.assigned === 'number'
    ? (members.find(m => m.id === filters.assigned)?.name ?? `Member ${filters.assigned}`)
    : null

  const filteredMembers = members.filter(m =>
    m.name.toLowerCase().includes(memberSearch.toLowerCase())
  )

  function handleMemberSelect(memberId: number | 'all' | 'me' | 'unassigned') {
    onChange({ assigned: memberId })
    setMemberDropdownOpen(false)
    setMemberSearch('')
  }

  return (
    <div className="space-y-3">
      {/* Filter row */}
      <div className="flex flex-wrap gap-2 items-center">
        {/* Search */}
        <div className="relative">
          <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none" />
          <input
            className="bg-input border border-default rounded-[5px] pl-8 pr-3 py-1.5 text-sm text-primary placeholder:text-muted-foreground focus:border-accent focus:outline-none w-48"
            placeholder="Search tickets..."
            value={filters.search}
            onChange={e => onChange({ search: e.target.value })}
          />
        </div>

        {/* Assignment — searchable member picker */}
        <div className="relative">
          <button
            onClick={() => { setMemberDropdownOpen(v => !v); setMemberSearch('') }}
            className={cn(
              'flex items-center gap-1.5 bg-input border rounded-[5px] px-3 py-1.5 text-sm focus:border-accent focus:outline-none',
              filters.assigned === 'all' ? 'text-muted-foreground border-default' : 'text-primary border-accent'
            )}
          >
            <User className="w-3.5 h-3.5" />
            {filters.assigned === 'all' && 'All Tickets'}
            {filters.assigned === 'me' && 'My Tickets'}
            {filters.assigned === 'unassigned' && 'Unassigned'}
            {currentMemberName}
          </button>
          {memberDropdownOpen && (
            <>
              <div className="fixed inset-0 z-10" onClick={() => setMemberDropdownOpen(false)} />
              <div className="absolute left-0 top-full mt-1 z-20 w-52 bg-card border border-default rounded-[5px] shadow-lg overflow-hidden">
                <div className="p-2 border-b border-default">
                  <input
                    autoFocus
                    className="w-full bg-input border border-default rounded-[5px] px-2 py-1 text-xs text-primary placeholder:text-muted-foreground focus:border-accent focus:outline-none"
                    placeholder="Search member..."
                    value={memberSearch}
                    onChange={e => setMemberSearch(e.target.value)}
                  />
                </div>
                <div className="max-h-48 overflow-y-auto py-1">
                  {!memberSearch && (
                    <>
                      <button onClick={() => handleMemberSelect('all')} className={cn('w-full text-left px-3 py-1.5 text-xs hover:bg-elevated transition-colors', filters.assigned === 'all' && 'text-accent')}>All Tickets</button>
                      <button onClick={() => handleMemberSelect('me')} className={cn('w-full text-left px-3 py-1.5 text-xs hover:bg-elevated transition-colors', filters.assigned === 'me' && 'text-accent')}>My Tickets</button>
                      <button onClick={() => handleMemberSelect('unassigned')} className={cn('w-full text-left px-3 py-1.5 text-xs hover:bg-elevated transition-colors', filters.assigned === 'unassigned' && 'text-accent')}>Unassigned</button>
                      {members.length > 0 && <div className="border-t border-default mx-2 my-1" />}
                    </>
                  )}
                  {filteredMembers.map(m => (
                    <button
                      key={m.id}
                      onClick={() => handleMemberSelect(m.id)}
                      className={cn('w-full text-left px-3 py-1.5 text-xs hover:bg-elevated transition-colors truncate', filters.assigned === m.id && 'text-accent')}
                    >
                      {m.name}
                    </button>
                  ))}
                  {memberSearch && filteredMembers.length === 0 && (
                    <p className="px-3 py-2 text-xs text-muted-foreground">No members found</p>
                  )}
                </div>
              </div>
            </>
          )}
        </div>

        {/* Board */}
        <select
          className="bg-input border border-default rounded-[5px] px-3 py-1.5 text-sm text-primary focus:border-accent focus:outline-none"
          value={filters.board_id ?? ''}
          onChange={e => onChange({ board_id: e.target.value ? Number(e.target.value) : null })}
        >
          <option value="">All Boards</option>
          {boards.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
        </select>

        {/* Status */}
        <select
          className="bg-input border border-default rounded-[5px] px-3 py-1.5 text-sm text-primary focus:border-accent focus:outline-none"
          value={filters.status_id ?? ''}
          onChange={e => onChange({ status_id: e.target.value ? Number(e.target.value) : null })}
        >
          <option value="">All Statuses</option>
          {statuses.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
        </select>

        {/* Priority */}
        <select
          className="bg-input border border-default rounded-[5px] px-3 py-1.5 text-sm text-primary focus:border-accent focus:outline-none"
          value={filters.priority ?? ''}
          onChange={e => onChange({ priority: e.target.value || null })}
        >
          <option value="">All Priorities</option>
          {priorities.map(p => <option key={p.id} value={p.name}>{p.name}</option>)}
        </select>

        {/* Include closed */}
        <label className="flex items-center gap-1.5 text-sm text-muted-foreground cursor-pointer select-none">
          <input
            type="checkbox"
            className="accent-accent"
            checked={filters.include_closed}
            onChange={e => onChange({ include_closed: e.target.checked })}
          />
          Include closed
        </label>

        {/* Clear filters */}
        {(filters.search || filters.board_id || filters.status_id || filters.priority || filters.assigned !== 'all' || filters.include_closed) && (
          <button
            onClick={() => onChange({ search: '', board_id: null, status_id: null, priority: null, assigned: 'all', include_closed: false, company_id: null })}
            className="flex items-center gap-1 text-xs text-muted-foreground hover:text-primary transition-colors"
          >
            <X className="w-3 h-3" /> Clear
          </button>
        )}
      </div>

      {/* Pagination row */}
      {total > 0 && (
        <div className="flex items-center justify-between text-xs text-muted-foreground">
          <span>
            {loading ? 'Loading…' : `Showing ${start}–${end} of ${total} tickets`}
          </span>
          <div className="flex gap-1">
            <button
              disabled={!hasPrev}
              onClick={() => onPageChange(page - 1)}
              className={cn(
                'px-2 py-1 rounded border text-xs transition-colors',
                hasPrev
                  ? 'border-default text-primary hover:border-hover'
                  : 'border-default text-muted-foreground opacity-40 cursor-not-allowed'
              )}
            >
              Prev
            </button>
            <button
              disabled={!hasNext}
              onClick={() => onPageChange(page + 1)}
              className={cn(
                'px-2 py-1 rounded border text-xs transition-colors',
                hasNext
                  ? 'border-default text-primary hover:border-hover'
                  : 'border-default text-muted-foreground opacity-40 cursor-not-allowed'
              )}
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
