'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { ChevronDown, Filter, X } from 'lucide-react'
import { cn } from '@/lib/utils'
import { getCountryName, getCountryFlag } from '@/lib/countries'

const ALL_STATUSES = [
  'SUBMITTED',
  'ELIGIBLE',
  'ASSIGNED',
  'SEMIFINALIST',
  'FINALIST',
  'REJECTED',
] as const

const STATUS_COLORS: Record<string, string> = {
  SUBMITTED: 'bg-gray-100 text-gray-700 hover:bg-gray-200',
  ELIGIBLE: 'bg-blue-100 text-blue-700 hover:bg-blue-200',
  ASSIGNED: 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200',
  SEMIFINALIST: 'bg-green-100 text-green-700 hover:bg-green-200',
  FINALIST: 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200',
  REJECTED: 'bg-red-100 text-red-700 hover:bg-red-200',
}

const ISSUE_LABELS: Record<string, string> = {
  POLLUTION_REDUCTION: 'Pollution Reduction',
  CLIMATE_MITIGATION: 'Climate Mitigation',
  TECHNOLOGY_INNOVATION: 'Technology Innovation',
  SUSTAINABLE_SHIPPING: 'Sustainable Shipping',
  BLUE_CARBON: 'Blue Carbon',
  HABITAT_RESTORATION: 'Habitat Restoration',
  COMMUNITY_CAPACITY: 'Community Capacity',
  SUSTAINABLE_FISHING: 'Sustainable Fishing',
  CONSUMER_AWARENESS: 'Consumer Awareness',
  OCEAN_ACIDIFICATION: 'Ocean Acidification',
  OTHER: 'Other',
}

export interface ProjectFilters {
  search: string
  statuses: string[]
  roundStates: string[]
  roundId: string
  competitionCategory: string
  oceanIssue: string
  country: string
  wantsMentorship: boolean | undefined
  hasFiles: boolean | undefined
  hasAssignments: boolean | undefined
}

export interface FilterOptions {
  countries: string[]
  categories: Array<{ value: string; count: number }>
  issues: Array<{ value: string; count: number }>
  rounds?: Array<{ id: string; name: string; programName: string; programYear: number }>
}

interface ProjectFiltersBarProps {
  filters: ProjectFilters
  filterOptions: FilterOptions | undefined
  onChange: (filters: ProjectFilters) => void
}

export function ProjectFiltersBar({
  filters,
  filterOptions,
  onChange,
}: ProjectFiltersBarProps) {
  const [isOpen, setIsOpen] = useState(false)

  const activeFilterCount = [
    filters.statuses.length > 0,
    filters.roundStates.length > 0,
    filters.roundId !== '',
    filters.competitionCategory !== '',
    filters.oceanIssue !== '',
    filters.country !== '',
    filters.wantsMentorship !== undefined,
    filters.hasFiles !== undefined,
    filters.hasAssignments !== undefined,
  ].filter(Boolean).length

  const toggleStatus = (status: string) => {
    const next = filters.statuses.includes(status)
      ? filters.statuses.filter((s) => s !== status)
      : [...filters.statuses, status]
    onChange({ ...filters, statuses: next })
  }

  const clearAll = () => {
    onChange({
      search: filters.search,
      statuses: [],
      roundStates: [],
      roundId: '',
      competitionCategory: '',
      oceanIssue: '',
      country: '',
      wantsMentorship: undefined,
      hasFiles: undefined,
      hasAssignments: undefined,
    })
  }

  return (
    <Collapsible open={isOpen} onOpenChange={setIsOpen}>
      <Card>
        <CollapsibleTrigger asChild>
          <CardHeader className="cursor-pointer hover:bg-muted/50 transition-colors py-3">
            <div className="flex items-center justify-between">
              <CardTitle className="text-base flex items-center gap-2">
                <Filter className="h-4 w-4" />
                Filters
                {activeFilterCount > 0 && (
                  <Badge variant="secondary" className="ml-1">
                    {activeFilterCount}
                  </Badge>
                )}
              </CardTitle>
              <ChevronDown
                className={cn(
                  'h-4 w-4 text-muted-foreground transition-transform duration-200',
                  isOpen && 'rotate-180'
                )}
              />
            </div>
          </CardHeader>
        </CollapsibleTrigger>
        <CollapsibleContent className="overflow-hidden data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0 data-[state=open]:slide-in-from-top-2 data-[state=closed]:slide-out-to-top-2 duration-200">
          <CardContent className="space-y-4 pt-0">
            {/* Status toggles */}
            <div className="space-y-2">
              <Label className="text-sm font-medium">Status</Label>
              <div className="flex flex-wrap gap-2">
                {ALL_STATUSES.map((status) => (
                  <button
                    key={status}
                    type="button"
                    onClick={() => toggleStatus(status)}
                    className={cn(
                      'rounded-full px-3 py-1 text-xs font-medium transition-colors',
                      filters.statuses.includes(status)
                        ? STATUS_COLORS[status]
                        : 'bg-muted text-muted-foreground hover:bg-muted/80'
                    )}
                  >
                    {status.replace('_', ' ')}
                  </button>
                ))}
              </div>
            </div>

            {/* Select filters grid */}
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
              <div className="space-y-2">
                <Label className="text-sm">Round / Edition</Label>
                <Select
                  value={filters.roundId || '_all'}
                  onValueChange={(v) =>
                    onChange({ ...filters, roundId: v === '_all' ? '' : v })
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="All rounds" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="_all">All rounds</SelectItem>
                    {filterOptions?.rounds?.map((s) => (
                      <SelectItem key={s.id} value={s.id}>
                        {s.name} ({s.programYear} {s.programName})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label className="text-sm">Category</Label>
                <Select
                  value={filters.competitionCategory || '_all'}
                  onValueChange={(v) =>
                    onChange({
                      ...filters,
                      competitionCategory: v === '_all' ? '' : v,
                    })
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="All categories" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="_all">All categories</SelectItem>
                    {filterOptions?.categories.map((c) => (
                      <SelectItem key={c.value} value={c.value}>
                        {c.value.replace('_', ' ')} ({c.count})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label className="text-sm">Ocean Issue</Label>
                <Select
                  value={filters.oceanIssue || '_all'}
                  onValueChange={(v) =>
                    onChange({ ...filters, oceanIssue: v === '_all' ? '' : v })
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="All issues" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="_all">All issues</SelectItem>
                    {filterOptions?.issues.map((i) => (
                      <SelectItem key={i.value} value={i.value}>
                        {ISSUE_LABELS[i.value] || i.value} ({i.count})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label className="text-sm">Country</Label>
                <Select
                  value={filters.country || '_all'}
                  onValueChange={(v) =>
                    onChange({ ...filters, country: v === '_all' ? '' : v })
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="All countries" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="_all">All countries</SelectItem>
                    {filterOptions?.countries
                      .map((c) => ({
                        code: c,
                        name: getCountryName(c),
                        flag: getCountryFlag(c),
                      }))
                      .sort((a, b) => a.name.localeCompare(b.name))
                      .map((c) => (
                        <SelectItem key={c.code} value={c.code}>
                          <span className="flex items-center gap-2">
                            <span>{c.flag}</span>
                            <span>{c.name}</span>
                          </span>
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Boolean toggles */}
            <div className="flex flex-wrap gap-6">
              <div className="flex items-center gap-2">
                <Switch
                  id="hasFiles"
                  checked={filters.hasFiles === true}
                  onCheckedChange={(checked) =>
                    onChange({
                      ...filters,
                      hasFiles: checked ? true : undefined,
                    })
                  }
                />
                <Label htmlFor="hasFiles" className="text-sm">
                  Has Documents
                </Label>
              </div>
              <div className="flex items-center gap-2">
                <Switch
                  id="hasAssignments"
                  checked={filters.hasAssignments === true}
                  onCheckedChange={(checked) =>
                    onChange({
                      ...filters,
                      hasAssignments: checked ? true : undefined,
                    })
                  }
                />
                <Label htmlFor="hasAssignments" className="text-sm">
                  Has Assignments
                </Label>
              </div>
              <div className="flex items-center gap-2">
                <Switch
                  id="wantsMentorship"
                  checked={filters.wantsMentorship === true}
                  onCheckedChange={(checked) =>
                    onChange({
                      ...filters,
                      wantsMentorship: checked ? true : undefined,
                    })
                  }
                />
                <Label htmlFor="wantsMentorship" className="text-sm">
                  Wants Mentorship
                </Label>
              </div>
            </div>

            {/* Clear all */}
            {activeFilterCount > 0 && (
              <div className="flex justify-end">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={clearAll}
                  className="text-muted-foreground"
                >
                  <X className="mr-1 h-3 w-3" />
                  Clear All Filters
                </Button>
              </div>
            )}
          </CardContent>
        </CollapsibleContent>
      </Card>
    </Collapsible>
  )
}
