import { useState, useEffect } from 'react'
import { Search, Calendar, X, Filter } from 'lucide-react'
import { DayPicker } from 'react-day-picker'
import type { DateRange } from 'react-day-picker'
import { format, startOfDay, endOfDay, startOfWeek, endOfWeek, startOfMonth, endOfMonth, subDays } from 'date-fns'
import 'react-day-picker/dist/style.css'
import { cn } from '@/lib/utils'
import type { TreeListItem } from '@/types'

export interface SessionFilterState {
  ticketNumber: string
  clientName: string
  treeName: string
  dateRange: DateRange | undefined
  dateType: 'started' | 'completed'
}

interface SessionFiltersProps {
  filters: SessionFilterState
  onChange: (filters: SessionFilterState) => void
  onClear: () => void
  trees: TreeListItem[]
}

const datePresets = [
  { label: 'Today', value: 'today' },
  { label: 'This Week', value: 'week' },
  { label: 'Last 7 Days', value: 'last7' },
  { label: 'This Month', value: 'month' },
]

export function SessionFilters({ filters, onChange, onClear, trees }: SessionFiltersProps) {
  const [showDatePicker, setShowDatePicker] = useState(false)
  const [localDateRange, setLocalDateRange] = useState<DateRange | undefined>(filters.dateRange)

  const filtersDateRange = filters.dateRange
  useEffect(() => {
    setLocalDateRange(filtersDateRange)
  }, [filtersDateRange])

  const handleFilterChange = (key: keyof SessionFilterState, value: SessionFilterState[keyof SessionFilterState]) => {
    onChange({ ...filters, [key]: value })
  }

  const applyDatePreset = (preset: string) => {
    const today = new Date()
    let range: DateRange | undefined

    switch (preset) {
      case 'today':
        range = { from: startOfDay(today), to: endOfDay(today) }
        break
      case 'week':
        range = { from: startOfWeek(today), to: endOfWeek(today) }
        break
      case 'last7':
        range = { from: subDays(today, 7), to: today }
        break
      case 'month':
        range = { from: startOfMonth(today), to: endOfMonth(today) }
        break
    }

    if (range) {
      setLocalDateRange(range)
      onChange({ ...filters, dateRange: range })
      setShowDatePicker(false)
    }
  }

  const clearDateRange = () => {
    setLocalDateRange(undefined)
    onChange({ ...filters, dateRange: undefined })
  }

  const formatDateRange = (range: DateRange | undefined) => {
    if (!range?.from) return 'Select date range'
    if (!range.to) return format(range.from, 'MMM d, yyyy')
    return `${format(range.from, 'MMM d')} - ${format(range.to, 'MMM d, yyyy')}`
  }

  const hasActiveFilters =
    filters.ticketNumber ||
    filters.clientName ||
    filters.treeName ||
    filters.dateRange?.from

  const uniqueTreeNames = Array.from(new Set(trees.map(t => t.name))).sort()

  return (
    <div className="space-y-4">
      {/* Main Filter Controls */}
      <div className="flex flex-col gap-3 sm:flex-row">
        {/* Ticket Number Search */}
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <input
            type="text"
            placeholder="Search by ticket number..."
            value={filters.ticketNumber}
            onChange={(e) => handleFilterChange('ticketNumber', e.target.value)}
            className={cn(
              'w-full rounded-md border border-border bg-card py-2 pl-9 pr-3',
              'text-foreground placeholder:text-muted-foreground',
              'focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20'
            )}
          />
        </div>

        {/* Client Name Search */}
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <input
            type="text"
            placeholder="Search by client name..."
            value={filters.clientName}
            onChange={(e) => handleFilterChange('clientName', e.target.value)}
            className={cn(
              'w-full rounded-md border border-border bg-card py-2 pl-9 pr-3',
              'text-foreground placeholder:text-muted-foreground',
              'focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20'
            )}
          />
        </div>

        {/* Tree Name Filter */}
        <select
          value={filters.treeName}
          onChange={(e) => handleFilterChange('treeName', e.target.value)}
          className={cn(
            'rounded-md border border-border bg-card px-3 py-2',
            'text-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/20',
            'sm:min-w-[200px]'
          )}
        >
          <option value="">All Trees</option>
          {uniqueTreeNames.map((name) => (
            <option key={name} value={name}>
              {name}
            </option>
          ))}
        </select>
      </div>

      {/* Date Range Filter */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
        <div className="relative flex-1">
          <button
            onClick={() => setShowDatePicker(!showDatePicker)}
            className={cn(
              'flex w-full items-center gap-2 rounded-md border border-border bg-card px-3 py-2 text-sm',
              'text-foreground hover:bg-accent',
              filters.dateRange?.from && 'border-primary/30'
            )}
          >
            <Calendar className="h-4 w-4 text-muted-foreground" />
            <span className={cn(!filters.dateRange?.from && 'text-muted-foreground')}>
              {formatDateRange(filters.dateRange)}
            </span>
          </button>

          {showDatePicker && (
            <div className="absolute left-0 top-full z-50 mt-2 rounded-lg border border-border bg-[#0a0a0a] p-4 shadow-lg">
              {/* Date Type Toggle */}
              <div className="mb-3 flex gap-2">
                <button
                  onClick={() => handleFilterChange('dateType', 'started')}
                  className={cn(
                    'flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
                    filters.dateType === 'started'
                      ? 'bg-gradient-brand text-white shadow-lg shadow-primary/20'
                      : 'border border-border text-muted-foreground hover:bg-accent hover:text-foreground'
                  )}
                >
                  Started
                </button>
                <button
                  onClick={() => handleFilterChange('dateType', 'completed')}
                  className={cn(
                    'flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
                    filters.dateType === 'completed'
                      ? 'bg-gradient-brand text-white shadow-lg shadow-primary/20'
                      : 'border border-border text-muted-foreground hover:bg-accent hover:text-foreground'
                  )}
                >
                  Completed
                </button>
              </div>

              {/* Quick Presets */}
              <div className="mb-3 grid grid-cols-2 gap-2">
                {datePresets.map((preset) => (
                  <button
                    key={preset.value}
                    onClick={() => applyDatePreset(preset.value)}
                    className={cn(
                      'rounded-md bg-accent px-3 py-1.5 text-sm font-medium text-muted-foreground',
                      'hover:bg-accent/80 hover:text-foreground'
                    )}
                  >
                    {preset.label}
                  </button>
                ))}
              </div>

              {/* Date Picker */}
              <DayPicker
                mode="range"
                selected={localDateRange}
                onSelect={(range) => {
                  setLocalDateRange(range)
                  if (range?.from && range?.to) {
                    onChange({ ...filters, dateRange: range })
                    setShowDatePicker(false)
                  }
                }}
                className="rdp-custom"
              />

              {/* Actions */}
              <div className="mt-3 flex gap-2">
                <button
                  onClick={() => {
                    if (localDateRange?.from && localDateRange?.to) {
                      onChange({ ...filters, dateRange: localDateRange })
                    }
                    setShowDatePicker(false)
                  }}
                  className={cn(
                    'flex-1 rounded-md bg-gradient-brand px-3 py-1.5 text-sm font-medium text-white shadow-lg shadow-primary/20',
                    'hover:opacity-90'
                  )}
                >
                  Apply
                </button>
                <button
                  onClick={() => setShowDatePicker(false)}
                  className={cn(
                    'rounded-md border border-border px-3 py-1.5 text-sm font-medium text-muted-foreground',
                    'hover:bg-accent hover:text-foreground'
                  )}
                >
                  Cancel
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Clear All Button */}
        {hasActiveFilters && (
          <button
            onClick={onClear}
            className={cn(
              'flex items-center gap-2 rounded-md border border-border px-3 py-2 text-sm font-medium',
              'text-muted-foreground hover:bg-accent hover:text-foreground'
            )}
          >
            <Filter className="h-4 w-4" />
            Clear All
          </button>
        )}
      </div>

      {/* Active Filter Chips */}
      {hasActiveFilters && (
        <div className="flex flex-wrap items-center gap-2">
          <span className="text-sm text-muted-foreground">Active filters:</span>
          {filters.ticketNumber && (
            <span className="inline-flex items-center gap-1 rounded-full bg-accent px-3 py-1 text-sm text-muted-foreground">
              Ticket: {filters.ticketNumber}
              <button
                onClick={() => handleFilterChange('ticketNumber', '')}
                className="rounded-full p-0.5 hover:bg-accent/80"
              >
                <X className="h-3 w-3" />
              </button>
            </span>
          )}
          {filters.clientName && (
            <span className="inline-flex items-center gap-1 rounded-full bg-accent px-3 py-1 text-sm text-muted-foreground">
              Client: {filters.clientName}
              <button
                onClick={() => handleFilterChange('clientName', '')}
                className="rounded-full p-0.5 hover:bg-accent/80"
              >
                <X className="h-3 w-3" />
              </button>
            </span>
          )}
          {filters.treeName && (
            <span className="inline-flex items-center gap-1 rounded-full bg-accent px-3 py-1 text-sm text-muted-foreground">
              Tree: {filters.treeName}
              <button
                onClick={() => handleFilterChange('treeName', '')}
                className="rounded-full p-0.5 hover:bg-accent/80"
              >
                <X className="h-3 w-3" />
              </button>
            </span>
          )}
          {filters.dateRange?.from && (
            <span className="inline-flex items-center gap-1 rounded-full bg-accent px-3 py-1 text-sm text-muted-foreground">
              {formatDateRange(filters.dateRange)} ({filters.dateType})
              <button
                onClick={clearDateRange}
                className="rounded-full p-0.5 hover:bg-accent/80"
              >
                <X className="h-3 w-3" />
              </button>
            </span>
          )}
        </div>
      )}
    </div>
  )
}
