'use client'

import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { X, Save, Filter } from 'lucide-react'
import { useSearchParams, useRouter } from 'next/navigation'

interface FilterPreset {
  id: string
  name: string
  filters: Record<string, any>
}

interface AdvancedFiltersProps {
  onFiltersChange: (filters: Record<string, any>) => void
  filterConfig: {
    multiSelect?: Array<{ key: string; label: string; options: string[] }>
    dateRange?: Array<{ key: string; label: string }>
    costRange?: Array<{ key: string; label: string; min: number; max: number }>
  }
  presets?: FilterPreset[]
  onSavePreset?: (preset: FilterPreset) => void
}

export function AdvancedFilters({
  onFiltersChange,
  filterConfig,
  presets = [],
  onSavePreset,
}: AdvancedFiltersProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [isOpen, setIsOpen] = useState(false)
  const [filters, setFilters] = useState<Record<string, any>>({})
  const [presetName, setPresetName] = useState('')

  // Load filters from URL
  useEffect(() => {
    const urlFilters: Record<string, any> = {}
    searchParams.forEach((value, key) => {
      if (key.startsWith('filter_')) {
        const filterKey = key.replace('filter_', '')
        try {
          urlFilters[filterKey] = JSON.parse(value)
        } catch {
          urlFilters[filterKey] = value
        }
      }
    })
    if (Object.keys(urlFilters).length > 0) {
      setFilters(urlFilters)
      onFiltersChange(urlFilters)
    }
  }, [searchParams, onFiltersChange])

  // Sync filters to URL
  const updateURL = useCallback(
    (newFilters: Record<string, any>) => {
      const params = new URLSearchParams(searchParams.toString())
      
      // Remove old filter params
      Array.from(params.keys())
        .filter((key) => key.startsWith('filter_'))
        .forEach((key) => params.delete(key))

      // Add new filter params
      Object.entries(newFilters).forEach(([key, value]) => {
        if (value !== null && value !== undefined && value !== '') {
          params.set(
            `filter_${key}`,
            typeof value === 'object' ? JSON.stringify(value) : String(value)
          )
        }
      })

      router.replace(`?${params.toString()}`, { scroll: false })
    },
    [searchParams, router]
  )

  const handleFilterChange = (key: string, value: any) => {
    const newFilters = { ...filters, [key]: value }
    setFilters(newFilters)
    onFiltersChange(newFilters)
    updateURL(newFilters)
  }

  const handleMultiSelectChange = (key: string, value: string, checked: boolean) => {
    const current = (filters[key] as string[]) || []
    const newValue = checked
      ? [...current, value]
      : current.filter((v) => v !== value)
    handleFilterChange(key, newValue.length > 0 ? newValue : null)
  }

  const handleDateRangeChange = (key: string, field: 'start' | 'end', value: string) => {
    const current = filters[key] || { start: '', end: '' }
    const newRange = { ...current, [field]: value }
    handleFilterChange(
      key,
      newRange.start || newRange.end ? newRange : null
    )
  }

  const handleCostRangeChange = (key: string, field: 'min' | 'max', value: number) => {
    const current = filters[key] || { min: 0, max: 1000000 }
    const newRange = { ...current, [field]: value }
    handleFilterChange(key, newRange)
  }

  const clearFilters = () => {
    setFilters({})
    onFiltersChange({})
    updateURL({})
  }

  const applyPreset = (preset: FilterPreset) => {
    setFilters(preset.filters)
    onFiltersChange(preset.filters)
    updateURL(preset.filters)
  }

  const saveCurrentAsPreset = () => {
    if (!presetName.trim() || !onSavePreset) return
    
    const preset: FilterPreset = {
      id: `preset-${Date.now()}`,
      name: presetName,
      filters: { ...filters },
    }
    onSavePreset(preset)
    setPresetName('')
  }

  const activeFilterCount = Object.values(filters).filter(
    (v) => v !== null && v !== undefined && v !== '' && (Array.isArray(v) ? v.length > 0 : true)
  ).length

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <Button
          variant="outline"
          onClick={() => setIsOpen(!isOpen)}
          className="flex items-center gap-2"
        >
          <Filter className="h-4 w-4" />
          Advanced Filters
          {activeFilterCount > 0 && (
            <Badge variant="default" className="ml-2">
              {activeFilterCount}
            </Badge>
          )}
        </Button>
        {activeFilterCount > 0 && (
          <Button variant="ghost" size="sm" onClick={clearFilters}>
            <X className="h-4 w-4 mr-2" />
            Clear All
          </Button>
        )}
      </div>

      {isOpen && (
        <Card>
          <CardHeader>
            <CardTitle>Filter Options</CardTitle>
            <CardDescription>Apply multiple filters to refine your results</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Multi-select filters */}
            {filterConfig.multiSelect?.map((config) => (
              <div key={config.key}>
                <Label>{config.label}</Label>
                <div className="mt-2 space-y-2 max-h-32 overflow-y-auto">
                  {config.options.map((option) => {
                    const selected = (filters[config.key] as string[])?.includes(option) || false
                    return (
                      <div key={option} className="flex items-center space-x-2">
                        <input
                          type="checkbox"
                          id={`${config.key}-${option}`}
                          checked={selected}
                          onChange={(e) =>
                            handleMultiSelectChange(config.key, option, e.target.checked)
                          }
                          className="rounded border-studio-medium"
                        />
                        <Label
                          htmlFor={`${config.key}-${option}`}
                          className="text-sm font-normal cursor-pointer"
                        >
                          {option}
                        </Label>
                      </div>
                    )
                  })}
                </div>
                {(filters[config.key] as string[])?.length > 0 && (
                  <div className="flex flex-wrap gap-1 mt-2">
                    {(filters[config.key] as string[]).map((value) => (
                      <Badge
                        key={value}
                        variant="outline"
                        className="cursor-pointer"
                        onClick={() => handleMultiSelectChange(config.key, value, false)}
                      >
                        {value}
                        <X className="h-3 w-3 ml-1" />
                      </Badge>
                    ))}
                  </div>
                )}
              </div>
            ))}

            {/* Date range filters */}
            {filterConfig.dateRange?.map((config) => (
              <div key={config.key} className="grid grid-cols-2 gap-4">
                <div>
                  <Label>{config.label} - Start</Label>
                  <Input
                    type="date"
                    value={(filters[config.key] as { start?: string })?.start || ''}
                    onChange={(e) => handleDateRangeChange(config.key, 'start', e.target.value)}
                    className="mt-1"
                  />
                </div>
                <div>
                  <Label>{config.label} - End</Label>
                  <Input
                    type="date"
                    value={(filters[config.key] as { end?: string })?.end || ''}
                    onChange={(e) => handleDateRangeChange(config.key, 'end', e.target.value)}
                    className="mt-1"
                  />
                </div>
              </div>
            ))}

            {/* Cost range filters */}
            {filterConfig.costRange?.map((config) => (
              <div key={config.key}>
                <Label>{config.label}</Label>
                <div className="grid grid-cols-2 gap-4 mt-2">
                  <div>
                    <Label className="text-xs text-studio-medium">Min</Label>
                    <Input
                      type="number"
                      min={config.min}
                      max={config.max}
                      value={(filters[config.key] as { min?: number })?.min || config.min}
                      onChange={(e) =>
                        handleCostRangeChange(config.key, 'min', Number(e.target.value))
                      }
                      className="mt-1"
                    />
                  </div>
                  <div>
                    <Label className="text-xs text-studio-medium">Max</Label>
                    <Input
                      type="number"
                      min={config.min}
                      max={config.max}
                      value={(filters[config.key] as { max?: number })?.max || config.max}
                      onChange={(e) =>
                        handleCostRangeChange(config.key, 'max', Number(e.target.value))
                      }
                      className="mt-1"
                    />
                  </div>
                </div>
              </div>
            ))}

            {/* Presets */}
            {presets.length > 0 && (
              <div>
                <Label>Saved Presets</Label>
                <div className="flex flex-wrap gap-2 mt-2">
                  {presets.map((preset) => (
                    <Button
                      key={preset.id}
                      variant="outline"
                      size="sm"
                      onClick={() => applyPreset(preset)}
                    >
                      {preset.name}
                    </Button>
                  ))}
                </div>
              </div>
            )}

            {/* Save preset */}
            {onSavePreset && (
              <div>
                <Label>Save Current Filters as Preset</Label>
                <div className="flex gap-2 mt-2">
                  <Input
                    placeholder="Preset name"
                    value={presetName}
                    onChange={(e) => setPresetName(e.target.value)}
                  />
                  <Button
                    size="sm"
                    onClick={saveCurrentAsPreset}
                    disabled={!presetName.trim()}
                  >
                    <Save className="h-4 w-4 mr-2" />
                    Save
                  </Button>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  )
}

