"use client"

import { Card, CardContent } from "@/components/ui/card"
import { DateRangeSelector, DateRangePreset } from "./DateRangeSelector"
import { MoodFilter } from "./MoodFilter"
import { DailyLogFilters as FilterTypes } from "@/types/daily-log"

interface DailyLogFiltersProps {
  filters: FilterTypes
  onFiltersChange: (filters: FilterTypes) => void
}

export function DailyLogFilters({
  filters,
  onFiltersChange,
}: DailyLogFiltersProps) {
  const handleDateRangeChange = (preset: DateRangePreset) => {
    const now = new Date()
    let startDate: Date

    switch (preset) {
      case "week":
        startDate = new Date(now)
        startDate.setDate(now.getDate() - 7)
        break
      case "month":
        startDate = new Date(now)
        startDate.setMonth(now.getMonth() - 1)
        break
      case "3months":
        startDate = new Date(now)
        startDate.setMonth(now.getMonth() - 3)
        break
      case "all":
        startDate = new Date(0) // Epoch
        break
    }

    onFiltersChange({
      ...filters,
      startDate: startDate.toISOString().split("T")[0],
      endDate: now.toISOString().split("T")[0],
    })
  }

  const handleMoodChange = (moods: number[]) => {
    onFiltersChange({
      ...filters,
      moods: moods.length > 0 ? moods : undefined,
    })
  }

  // Detectar preset actual
  const currentPreset = (): DateRangePreset => {
    if (!filters.startDate) return "all"

    const now = new Date()
    const start = new Date(filters.startDate)
    const daysDiff = Math.round(
      (now.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)
    )

    if (daysDiff <= 7) return "week"
    if (daysDiff <= 31) return "month"
    if (daysDiff <= 93) return "3months"
    return "all"
  }

  return (
    <Card>
      <CardContent className="p-4">
        <div className="space-y-3">
          <DateRangeSelector
            value={currentPreset()}
            onChange={handleDateRangeChange}
          />
          <MoodFilter
            selectedMoods={filters.moods || []}
            onChange={handleMoodChange}
          />
        </div>
      </CardContent>
    </Card>
  )
}
