'use client'

import React from 'react'
import { Trade, DayStats } from '@/types/trade'
import { useState, useEffect } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { Card } from "@/components/ui/card"
import { DayTradesModal } from '@/components/day-trades-modal'
import YearlyStats from '@/components/yearlystats'
import AddTradeModal from '@/components/AddTradeModal'

interface WeeklyStats {
  weekNumber: number
  trades: number
  winRate: number
  avgGain: number
  avgLoss: number
  biggestGain: number
  biggestLoss: number
  pnl: number
}

interface MonthlyStats {
  pnl: number
  winRate: number
  totalTrades: number
  profitFactor: number
  averageRR: number
  averageWin: number
  averageLoss: number
  averageHoldingTime: string
}

export default function CalendarPage() {
  const [trades, setTrades] = useState<Trade[]>([])
  const [currentDate, setCurrentDate] = useState(new Date())
  const [loading, setLoading] = useState(true)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [currentView, setCurrentView] = useState<'monthly' | 'yearly'>('monthly')
  const [selectedDay, setSelectedDay] = useState<{
    day: number;
    trades: Trade[];
    stats: DayStats | null;
  } | null>(null)
  const [isAddTradeModalOpen, setIsAddTradeModalOpen] = useState(false)

  // Fetch Trades Function
  const fetchTrades = async () => {
    try {
      const response = await fetch('/api/trades')
      if (!response.ok) throw new Error('Failed to fetch trades')
      const data = await response.json()

      const tradesWithDates = data.trades.map((trade: any) => ({
        ...trade,
        entry_date: new Date(trade.entry_date),
        exit_date: new Date(trade.exit_date),
        created_at: new Date(trade.created_at),
        updated_at: new Date(trade.updated_at)
      }))

      setTrades(tradesWithDates)
    } catch (error) {
      console.error('Error fetching trades:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchTrades()
  }, [])

  const handleNewTrade = async (newTrade: Trade) => {
    setTrades(prevTrades => [...prevTrades, {
      ...newTrade,
      entry_date: new Date(newTrade.entry_date),
      exit_date: new Date(newTrade.exit_date),
      created_at: new Date(),
      updated_at: new Date()
    }])

    if (selectedDay) {
      const newTradeDate = new Date(newTrade.entry_date)
      if (
        newTradeDate.getDate() === selectedDay.day &&
        newTradeDate.getMonth() === currentDate.getMonth() &&
        newTradeDate.getFullYear() === currentDate.getFullYear()
      ) {
        const updatedDayTrades = [...selectedDay.trades, newTrade]
        setSelectedDay({
          day: selectedDay.day,
          trades: updatedDayTrades,
          stats: calculateDayStats(updatedDayTrades)
        })
      }
    }
  }

  // Helper Functions
  const getWeekNumber = (date: Date): number => {
    const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1)
    return Math.ceil((date.getDate() + firstDayOfMonth.getDay()) / 7)
  }

  const getDaysInMonth = (date: Date): number => {
    return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate()
  }

  const getTradesForDay = (day: number): Trade[] => {
    const date = new Date(currentDate.getFullYear(), currentDate.getMonth(), day)
    return trades.filter(trade => {
      const tradeDate = new Date(trade.entry_date)
      return tradeDate.getDate() === day &&
        tradeDate.getMonth() === date.getMonth() &&
        tradeDate.getFullYear() === date.getFullYear()
    })
  }

  const calculateDayStats = (dayTrades: Trade[]): DayStats | null => {
    if (!dayTrades.length) return null

    const totalPnL = dayTrades.reduce((sum, trade) => sum + trade.pnl, 0)
    const wins = dayTrades.filter(trade => trade.pnl > 0).length

    return {
      pnl: totalPnL,
      winRate: `${wins}W-${dayTrades.length - wins}L`,
      winRatePercent: (wins / dayTrades.length) * 100
    }
  }

  const calculateWeeklyStats = (trades: Trade[], weekStart: Date, weekEnd: Date): WeeklyStats => {
    const weekTrades = trades.filter(trade => {
      const tradeDate = new Date(trade.entry_date)
      return tradeDate >= weekStart && tradeDate <= weekEnd
    })

    const wins = weekTrades.filter(trade => trade.pnl > 0)
    const losses = weekTrades.filter(trade => trade.pnl < 0)

    return {
      weekNumber: getWeekNumber(weekStart),
      trades: weekTrades.length,
      winRate: weekTrades.length ? (wins.length / weekTrades.length) * 100 : 0,
      avgGain: wins.length ? wins.reduce((sum, trade) => sum + trade.pnl, 0) / wins.length : 0,
      avgLoss: losses.length ? losses.reduce((sum, trade) => sum + trade.pnl, 0) / losses.length : 0,
      biggestGain: wins.length ? Math.max(...wins.map(trade => trade.pnl)) : 0,
      biggestLoss: losses.length ? Math.min(...losses.map(trade => trade.pnl)) : 0,
      pnl: weekTrades.reduce((sum, trade) => sum + trade.pnl, 0)
    }
  }

  const calculateMonthlyStats = (trades: Trade[]): MonthlyStats => {
    const wins = trades.filter(trade => trade.pnl > 0)
    const losses = trades.filter(trade => trade.pnl < 0)

    const totalPnl = trades.reduce((sum, trade) => sum + trade.pnl, 0)
    const winRate = trades.length ? (wins.length / trades.length) * 100 : 0
    const avgWin = wins.length ? wins.reduce((sum, trade) => sum + trade.pnl, 0) / wins.length : 0
    const avgLoss = losses.length ? losses.reduce((sum, trade) => sum + trade.pnl, 0) / losses.length : 0

    return {
      pnl: totalPnl,
      winRate,
      totalTrades: trades.length,
      profitFactor: Math.abs(avgLoss) ? avgWin / Math.abs(avgLoss) : 0,
      averageRR: 1.94,
      averageWin: avgWin,
      averageLoss: avgLoss,
      averageHoldingTime: "5h 22m"
    }
  }

  const changeMonth = (increment: number) => {
    const newDate = new Date(currentDate)
    if (currentView === 'monthly') {
      newDate.setMonth(newDate.getMonth() + increment)
    } else {
      newDate.setFullYear(newDate.getFullYear() + increment)
    }
    setCurrentDate(newDate)
  }

  const handleViewChange = (view: 'monthly' | 'yearly') => {
    setCurrentView(view)
    if (view === 'yearly') {
      setCurrentDate(new Date(currentDate.getFullYear(), 0, 1))
    } else {
      const now = new Date()
      setCurrentDate(new Date(now.getFullYear(), now.getMonth(), 1))
    }
  }

  const handleCellClick = (day: number) => {
    const dayTrades = getTradesForDay(day)
    const stats = calculateDayStats(dayTrades)

    setSelectedDay({
      day,
      trades: dayTrades,
      stats
    })
    setIsModalOpen(true)
  }

  // Add new navigation function
  const navigateDay = (increment: number) => {
    if (!selectedDay) return

    const daysInMonth = getDaysInMonth(currentDate)
    let newDay = selectedDay.day + increment

    // Handle month boundaries
    if (newDay < 1) {
      newDay = daysInMonth
    } else if (newDay > daysInMonth) {
      newDay = 1
    }

    const newDayTrades = getTradesForDay(newDay)
    const stats = calculateDayStats(newDayTrades)

    setSelectedDay({
      day: newDay,
      trades: newDayTrades,
      stats
    })
  }

  // Add keyboard navigation effect
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!isModalOpen) return

      if (e.key === 'ArrowLeft') {
        navigateDay(-1)
      } else if (e.key === 'ArrowRight') {
        navigateDay(1)
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [isModalOpen, selectedDay, currentDate])

  const renderYearlyView = () => {
    const renderMonthDays = (monthIndex: number) => {
      const monthDate = new Date(currentDate.getFullYear(), monthIndex, 1)
      const daysInMonth = getDaysInMonth(monthDate)
      const firstDay = new Date(currentDate.getFullYear(), monthIndex, 1).getDay()
      const days: (number | null)[] = []

      // Add empty days for the first week
      for (let i = 0; i < firstDay; i++) {
        days.push(null)
      }

      // Add actual days
      for (let day = 1; day <= daysInMonth; day++) {
        days.push(day)
      }

      // Add remaining empty days
      while (days.length % 7 !== 0) {
        days.push(null)
      }

      // Create weeks array
      const weeks = []
      for (let i = 0; i < days.length; i += 7) {
        weeks.push(days.slice(i, i + 7))
      }

      return weeks
    }

    const getDayPnL = (monthIndex: number, day: number) => {
      const dayTrades = trades.filter(trade => {
        const tradeDate = new Date(trade.entry_date)
        return (
          tradeDate.getFullYear() === currentDate.getFullYear() &&
          tradeDate.getMonth() === monthIndex &&
          tradeDate.getDate() === day
        )
      })

      return dayTrades.reduce((sum, trade) => sum + trade.pnl, 0)
    }

    const calculateMonthlyStats = (monthIndex: number) => {
      const monthTrades = trades.filter(trade => {
        const tradeDate = new Date(trade.entry_date)
        return tradeDate.getMonth() === monthIndex &&
          tradeDate.getFullYear() === currentDate.getFullYear()
      })

      const wins = monthTrades.filter(trade => trade.pnl > 0)
      const losses = monthTrades.filter(trade => trade.pnl < 0)

      return {
        trades: monthTrades.length,
        winRate: monthTrades.length ? (wins.length / monthTrades.length) * 100 : 0,
        avgGain: wins.length ? wins.reduce((sum, trade) => sum + trade.pnl, 0) / wins.length : 0,
        avgLoss: losses.length ? losses.reduce((sum, trade) => sum + trade.pnl, 0) / losses.length : 0,
        biggestGain: wins.length ? Math.max(...wins.map(trade => trade.pnl)) : 0,
        biggestLoss: losses.length ? Math.min(...losses.map(trade => trade.pnl)) : 0,
        pnl: monthTrades.reduce((sum, trade) => sum + trade.pnl, 0),
      }
    }

    const yearlyTotalPnL = trades
      .filter(trade => new Date(trade.entry_date).getFullYear() === currentDate.getFullYear())
      .reduce((sum, trade) => sum + trade.pnl, 0)

    return (
      <>
        <div className="grid grid-cols-4 gap-2 p-4">
          {Array.from({ length: 12 }, (_, monthIndex) => {
            const monthDate = new Date(currentDate.getFullYear(), monthIndex, 1)
            const monthName = monthDate.toLocaleString('default', { month: 'short' })
            const weeks = renderMonthDays(monthIndex)

            return (
              <Card
                key={monthName}
                className="p-4 bg-gray-900/30 hover:bg-gray-900/40 cursor-pointer w-full"
                onClick={() => {
                  setCurrentDate(new Date(currentDate.getFullYear(), monthIndex, 1))
                  setCurrentView('monthly')
                }}
              >
                <div className="space-y-3 w-full">
                  <h3 className="text-lg font-bold text-gray-400">{monthName}</h3>
                  <div className="grid grid-cols-7 gap-1">
                    {['S', 'M', 'T', 'W', 'T', 'F', 'S'].map(day => (
                      <div key={day} className="text-center text-gray-600 text-xs pb-2">
                        {day}
                      </div>
                    ))}
                    {weeks.map((week, weekIndex) =>
                      week.map((day, dayIndex) => {
                        if (!day) return (
                          <div
                            key={`${weekIndex}-${dayIndex}`}
                            className="aspect-square"
                          />
                        )

                        const pnl = getDayPnL(monthIndex, day)
                        const bgColor = pnl > 0
                          ? 'bg-emerald-900/30'
                          : pnl < 0
                            ? 'bg-red-900/30'
                            : 'bg-gray-800/20'

                        return (
                          <div
                            key={`${weekIndex}-${dayIndex}`}
                            className={`aspect-square flex items-center justify-center text-xs ${bgColor} rounded`}
                          >
                            <span className="text-gray-300">{day}</span>
                          </div>
                        )
                      })
                    )}
                  </div>
                </div>
              </Card>
            )
          })}
        </div>

        {/* Yearly Statistics Section */}
        <div className="mt-8 space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 px-4">
            <Card className="p-4">
              <h3 className="text-sm font-medium text-gray-500">Yearly PnL</h3>
              <p className={`text-2xl font-bold ${yearlyTotalPnL >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                {yearlyTotalPnL >= 0 ? '+' : ''}${yearlyTotalPnL.toFixed(2)}
              </p>
            </Card>
          </div>

          <Card className="mx-4 p-6">
            <h3 className="text-lg font-semibold mb-4">Monthly Overview</h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="text-left border-b dark:border-gray-700">
                    <th className="pb-2 text-sm font-medium text-gray-500">Month</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Trades</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Win %</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Avg Gain</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Avg Loss</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Biggest Gain</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Biggest Loss</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">PnL</th>
                  </tr>
                </thead>
                <tbody className="divide-y dark:divide-gray-700">
                  {Array.from({ length: 12 }, (_, monthIndex) => {
                    const stats = calculateMonthlyStats(monthIndex)
                    const monthName = new Date(currentDate.getFullYear(), monthIndex).toLocaleString('default', { month: 'long' })

                    return (
                      <tr key={monthIndex} className="text-sm">
                        <td className="py-3">{monthName}</td>
                        <td>{stats.trades}</td>
                        <td>{stats.winRate.toFixed(1)}%</td>
                        <td className="text-green-600">
                          {stats.avgGain > 0 ? `+$${stats.avgGain.toFixed(2)}` : '$0.00'}
                        
                        
                          {stats.avgLoss < 0 ? `$${stats.avgLoss.toFixed(2)}` : '$0.00'}
                        </td>
                        <td className="text-green-600">
                          {stats.biggestGain > 0 ? `+$${stats.biggestGain.toFixed(2)}` : '$0.00'}
                        
                        
                          {stats.biggestLoss < 0 ? `$${stats.biggestLoss.toFixed(2)}` : '$0.00'}
                        </td>
                        <td className={stats.pnl >= 0 ? 'text-green-600' : 'text-red-600'}>
                          {stats.pnl !== 0 ? `${stats.pnl > 0 ? '+' : ''}$${stats.pnl.toFixed(2)}` : '$0.00'}
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
          </Card>
        </div>
      )
    }

    const renderDayCell = (day: number | null) => {
      const baseCellClasses = "p-0 relative h-28 w-full transition-all duration-200 hover:opacity-90 cursor-pointer"
      const baseContentClasses = "absolute inset-0 flex flex-col items-center justify-start p-2"

      if (day === null) {
        return (
          <td className="p-0" key={`empty-${Math.random()}`}>
            <div className={`${baseCellClasses} bg-gray-50 dark:bg-gray-800/20`} />
          </td>
        )
      }

      const isToday =
        day === new Date().getDate() &&
        currentDate.getMonth() === new Date().getMonth() &&
        currentDate.getFullYear() === new Date().getFullYear()

      const dayTrades = getTradesForDay(day)
      const stats = calculateDayStats(dayTrades)

      return (
        <td key={day} className="p-0">
          <div
            onClick={() => handleCellClick(day)}
            className={`
              ${baseCellClasses}
              ${stats ? (
                stats.pnl > 0
                  ? 'bg-emerald-100 dark:bg-emerald-900/30'
                  : 'bg-red-100 dark:bg-red-900/30'
              ) : 'bg-gray-50 dark:bg-gray-800/20'}
            `}
          >
            <div className="absolute top-2 left-2 text-sm font-medium text-gray-500 dark:text-gray-400">
              {day}
            </div>

            {isToday && (
              <div className="absolute top-2 right-2 w-2 h-2 rounded-full bg-red-500 animate-pulse" />
            )}

            {stats && (
              <div className={baseContentClasses}>
                <div className="mt-6 text-xl font-bold text-gray-900 dark:text-gray-100">
                  ${Math.abs(stats.pnl).toFixed(2)}
                </div>
                <div className="mt-1 text-sm text-gray-600 dark:text-gray-300">
                  {dayTrades.length} {dayTrades.length === 1 ? 'trade' : 'trades'}
                </div>
              </div>
            )}
          </div>
        </td>
      )
    }

    const renderCalendarGrid = () => {
      const days = getDaysInMonth(currentDate)
      const firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).getDay()
      const calendarDays: (number | null)[] = []

      for (let i = 0; i < firstDay; i++) {
        calendarDays.push(null)
      }

      for (let day = 1; day <= days; day++) {
        calendarDays.push(day)
      }

      while (calendarDays.length % 7 !== 0) {
        calendarDays.push(null)
      }

      const weeks = []
      for (let i = 0; i < calendarDays.length; i += 7) {
        weeks.push(calendarDays.slice(i, i + 7))
      }

      return weeks.map((week, weekIndex) => (
        <tr key={weekIndex} className="text-center">
          {week.map((day, dayIndex) => (
            <React.Fragment key={dayIndex}>
              {renderDayCell(day)}
            </React.Fragment>
          ))}
        </tr>
      ))
    }

    const renderStatistics = () => {
      const monthlyStats = calculateMonthlyStats(trades)

      return (
        <div className="mt-8 space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <Card className="p-4">
              <h3 className="text-sm font-medium text-gray-500">Monthly PnL</h3>
              <p className={`text-2xl font-bold ${monthlyStats.pnl >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                {monthlyStats.pnl >= 0 ? '+' : ''}{monthlyStats.pnl.toFixed(2)}
              </p>
            </Card>

            <Card className="p-4">
              <h3 className="text-sm font-medium text-gray-500">Win Rate</h3>
              <p className="text-2xl font-bold">{monthlyStats.winRate.toFixed(1)}%</p>
            </Card>

            <Card className="p-4">
              <h3 className="text-sm font-medium text-gray-500">Total Trades</h3>
              <p className="text-2xl font-bold">{monthlyStats.totalTrades}</p>
            </Card>

            <Card className="p-4">
              <h3 className="text-sm font-medium text-gray-500">Profit Factor</h3>
              <p className="text-2xl font-bold">{monthlyStats.profitFactor.toFixed(2)}</p>
            </Card>
          </div>

          <Card className="p-6">
            <h3 className="text-lg font-semibold mb-4">Statistics</h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
              <div className="space-y-6">
                <div>
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm text-gray-500">Average RR</span>
                    <span className="text-sm font-medium">{monthlyStats.averageRR}</span>
                  </div>
                  <div className="h-2 bg-gray-100 rounded-full">
                    <div
                      className="h-full bg-blue-500 rounded-full"
                      style={{ width: `${(monthlyStats.averageRR / 3) * 100}%` }}
                    />
                  </div>
                </div>

                <div>
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm text-gray-500">Win Rate</span>
                    <span className="text-sm font-medium">{monthlyStats.winRate.toFixed(1)}%</span>
                  </div>
                  <div className="h-2 bg-gray-100 rounded-full">
                    <div
                      className="h-full bg-green-500 rounded-full"
                      style={{ width: `${monthlyStats.winRate}%` }}
                    />
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <div>
                  <span className="text-sm text-gray-500">Average Win</span>
                  <p className="text-lg font-semibold text-green-600">
                    +${monthlyStats.averageWin.toFixed(2)}
                  </p>
                </div>
                <div>
                  <span className="text-sm text-gray-500">Average Loss</span>
                  <p className="text-lg font-semibold text-red-600">
                    ${monthlyStats.averageLoss.toFixed(2)}
                  </p>
                </div>
              </div>

              <div>
                <span className="text-sm text-gray-500">Average Holding Time</span>
                <p className="text-lg font-semibold">{monthlyStats.averageHoldingTime}</p>
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <h3 className="text-lg font-semibold mb-4">Weekly Overview</h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="text-left border-b dark:border-gray-700">
                    <th className="pb-2 text-sm font-medium text-gray-500">Week</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Trades</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Win %</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Avg Gain</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Avg Loss</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Biggest Gain</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">Biggest Loss</th>
                    <th className="pb-2 text-sm font-medium text-gray-500">PnL</th>
                  </tr>
                </thead>
                <tbody className="divide-y dark:divide-gray-700">
                  {[1, 2, 3, 4].map(weekNum => {
                    const weekStart = new Date(
                      currentDate.getFullYear(),
                      currentDate.getMonth(),
                      (weekNum - 1) * 7 + 1
                    )
                    const weekEnd = new Date(
                      currentDate.getFullYear(),
                      currentDate.getMonth(),
                      weekNum * 7
                    )
                    const stats = calculateWeeklyStats(trades, weekStart, weekEnd)

                    return (
                      <tr key={weekNum} className="text-sm">
                        <td className="py-3">Week {weekNum}</td>
                        <td>{stats.trades}</td>
                        <td>{stats.winRate.toFixed(1)}%</td>
                        <td className="text-green-600">+${stats.avgGain.toFixed(2)}</td>
                        <td className="text-red-600">${stats.avgLoss.toFixed(2)}</td>
                        <td className="text-green-600">+${stats.biggestGain.toFixed(2)}</td>
                        <td className="text-red-600">${stats.biggestLoss.toFixed(2)}</td>
                        <td className={stats.pnl >= 0 ? 'text-green-600' : 'text-red-600'}>
                          {stats.pnl >= 0 ? '+' : ''}${stats.pnl.toFixed(2)}
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
          </Card>
        </div>
      )
    }

    if (loading) {
      return (
        <div className="flex items-center justify-center min-h-screen">
          <div className="text-lg">Loading...</div>
        </div>
      )
    }

    return (
      <div className="dark:bg-gray-900 min-h-screen">
        <div className="flex items-center justify-between py-4 px-6 border-b border-gray-800">
          <div className="flex-1" />

          <div className="flex items-center gap-2">
            <button
              onClick={() => changeMonth(-1)}
              className="p-1.5 hover:bg-gray-800 rounded-full transition-colors"
            >
              <ChevronLeft className="h-5 w-5" />
            </button>

            <h2 className="text-2xl font-bold px-2">
              {currentView === 'monthly'
                ? currentDate.toLocaleString('default', { month: 'long', year: 'numeric' })
                : currentDate.getFullYear().toString()
              }
            </h2>

            <button
              onClick={() => changeMonth(1)}
              className="p-1.5 hover:bg-gray-800 rounded-full transition-colors"
            >
              <ChevronRight className="h-5 w-5" />
            </button>
          </div>

          <div className="flex-1 flex justify-end mr-6">
            <div className="flex bg-[#1E2538] rounded-full p-1"> {/* componentBg color from the HTML */}
              <button
                onClick={() => handleViewChange('monthly')}
                className={`text-sm font-bold rounded-full px-4 py-2 transition-colors ${currentView === 'monthly'
                  ? 'bg-[#25287a] text-[#264ecf]' /* blueSecondary when selected */
                  : 'text-[#94A3B8]' /* textSecondary color for unselected */
                  }`}
              >
                Monthly
              </button>
              <button
                onClick={() => handleViewChange('yearly')}
                className={`text-sm font-bold rounded-full px-4 py-2 transition-colors ${currentView === 'yearly'
                  ? 'bg-[#25287a] text-[#264ecf]' /* blueSecondary when selected */
                  : 'text-[#657283]' /* textSecondary color for unselected */
                  }`}
              >
                Yearly
              </button>
            </div>
          </div>
        </div>

        {currentView === 'monthly' ? (
          <>
            <div className="p-4">
              <div className="overflow-x-auto">
                <table className="w-full table-fixed border-separate border-spacing-1.5 lg:border-spacing-2">
                  <thead>
                    <tr>
                      {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(day => (
                        <th key={day} className="text-sm lg:text-base font-bold text-gray-600 dark:text-gray-400 pb-2 w-1/7">
                          {day}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {renderCalendarGrid()}
                  </tbody>
                </table>
              </div>
            </div>
            {renderStatistics()}
          </>
        ) : (
          renderYearlyView()
        )}

        <DayTradesModal
          isOpen={isModalOpen}
          onClose={() => setIsModalOpen(false)}
          selectedDay={selectedDay}
          currentDate={currentDate}
          onNewTrade={handleNewTrade}
          onNavigate={navigateDay} // Add this new prop
        />
      </div>
    )
}

take the previous code and to the following changes:

change1:
 <td className="text-green-600">
  {stats.avgGain > 0 ? `+$${stats.avgGain.toFixed(2)}` : '$0.00'}

// This should be a separate td cell:
  {stats.avgLoss < 0 ? `$${stats.avgLoss.toFixed(2)}` : '$0.00'}
</td>

change 2:
// In the yearly view table, fix the cells:
<tr key={monthIndex} className="text-sm">
  <td className="py-3">{monthName}</td>
  <td>{stats.trades}</td>
  <td>{stats.winRate.toFixed(1)}%</td>
  <td className="text-green-600">
    {stats.avgGain > 0 ? `+$${stats.avgGain.toFixed(2)}` : '$0.00'}
  </td>
  <td className="text-red-600">
    {stats.avgLoss < 0 ? `$${stats.avgLoss.toFixed(2)}` : '$0.00'}
  </td>
  <td className="text-green-600">
    {stats.biggestGain > 0 ? `+$${stats.biggestGain.toFixed(2)}` : '$0.00'}
  </td>
  <td className="text-red-600">
    {stats.biggestLoss < 0 ? `$${stats.biggestLoss.toFixed(2)}` : '$0.00'}
  </td>
  <td className={stats.pnl >= 0 ? 'text-green-600' : 'text-red-600'}>
    {stats.pnl !== 0 ? `${stats.pnl > 0 ? '+' : ''}$${stats.pnl.toFixed(2)}` : '$0.00'}
  </td>
</tr>

and return me the full updated code without errors