"use client"
import { Card, CardHeader, CardContent, CardTitle, CardDescription } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { RevenueChartActual } from "./RevenueChartActual"
import { useGetWeeklyEarnings } from "@/lib/react-query/hooks/analytics"
import { useState } from "react"
import { useTranslations } from "next-intl"

export function RevenueEvolutionCard({ className = "" }: { className?: string }) {
  const td = useTranslations('dashboard')
  const [range, setRange] = useState("daily")
  const { data: weeklyEarnings } = useGetWeeklyEarnings(range)

  // Calculate weekly total and daily average from API data
  const weeklyTotal = weeklyEarnings?.reduce((sum, day) => sum + day.earnings, 0) || 0
  const dailyAverage = weeklyEarnings && weeklyEarnings.length > 0 ? Math.round(weeklyTotal / weeklyEarnings.length) : 0

  return (
    <Card className={`bg-white rounded-xl shadow-sm ${className} gap-2`}>
      <CardHeader className="flex flex-row items-start justify-between space-y-0">
        <div className="space-y-1">
          <CardTitle className="font-medium text-primary-blue">{td('revenueEvolution.title')}</CardTitle>
          <CardDescription className="text-xs text-muted-foreground">
            {td('revenueEvolution.description')}
          </CardDescription>
        </div>
        <Select value={range} onValueChange={setRange}>
          <SelectTrigger className="w-[120px] h-9">
            <SelectValue placeholder="Select range" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="daily">{td('revenueEvolution.dailyTotal')}</SelectItem>
            <SelectItem value="weekly">{td('revenueEvolution.weeklyTotal')}</SelectItem>
            <SelectItem value="monthly">{td('revenueEvolution.monthlyTotal')}</SelectItem>
          </SelectContent>
        </Select>
      </CardHeader>

      <CardContent>
        <div className="flex gap-4 mb-4">
          <div className="bg-green-300/30 rounded-lg px-3 py-2 text-xs flex-1">
            <div className="font-bold text-black">
              {range === 'daily' ? td('revenueEvolution.dailyTotal') : 
               range === 'weekly' ? td('revenueEvolution.weeklyTotal') : 
               td('revenueEvolution.monthlyTotal')}
            </div>
            <div className="text-black text-base">€{weeklyTotal.toLocaleString()}</div>
          </div>

          <div className="bg-blue-300/30 rounded-lg px-3 py-2 text-xs flex-1">
            <div className="font-bold text-black">{td('revenueEvolution.dailyAverage')}</div>
            <div className="text-black text-base">€{dailyAverage.toLocaleString()}</div>
          </div>
        </div>

        {/* Chart */}
        <RevenueChartActual />
      </CardContent>
    </Card>
  )
}
