you have this code:'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'

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 [selectedDay, setSelectedDay] = useState<{
    day: number;
    trades: Trade[];
    stats: DayStats | null;
  } | null>(null)

  useEffect(() => {
    async function fetchTrades() {
      try {
        const response = await fetch('/api/trades')
        if (!response.ok) throw new Error('Failed to fetch trades')
        const data = await response.json()
        
        // Transform the dates in the response
        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)
      }
    }

    fetchTrades()
  }, [])

  // 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, // This should be calculated based on your risk per trade
      averageWin: avgWin,
      averageLoss: avgLoss,
      averageHoldingTime: "5h 22m" // This should be calculated from actual trade durations
    }
  }

  const changeMonth = (increment: number) => {
    const newDate = new Date(currentDate)
    newDate.setMonth(newDate.getMonth() + increment)
    setCurrentDate(newDate)
  }

  const handleCellClick = (day: number) => {
    const dayTrades = getTradesForDay(day)
    const stats = calculateDayStats(dayTrades)
    
    setSelectedDay({
      day,
      trades: dayTrades,
      stats
    })
    setIsModalOpen(true)
  }

  // Rendering Functions
  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">
          <div className={`${baseCellClasses} bg-gray-50 dark:bg-gray-800/20`} />
        </td>
      )
    }

    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>
  
          {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)[] = []

    // Fill in blank days before the first day of the month
    for (let i = 0; i < firstDay; i++) {
      calendarDays.push(null)
    }

    // Fill in the days of the month
    for (let day = 1; day <= days; day++) {
      calendarDays.push(day)
    }

    // Fill in any remaining days to complete the last week
    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">
        {/* Monthly Overview */}
        <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>

        {/* Statistics Section */}
        <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>

        {/* Weekly Overview */}
        <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 (
    <Card className="bg-white dark:bg-gray-900 w-[95%] lg:w-[90%] xl:w-[85%] mx-auto">
      <div className="flex justify-between items-center py-2 px-4 border-b border-gray-200 dark:border-gray-800">
        <button 
          onClick={() => changeMonth(-1)} 
          className="p-1.5 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
        >
          <ChevronLeft className="h-4 w-4 lg:h-5 lg:w-5" />
        </button>
        <h2 className="text-xl lg:text-2xl font-bold tracking-tight">
          {currentDate.toLocaleString('default', { month: 'long', year: 'numeric' })}
        </h2>
        <button 
          onClick={() => changeMonth(1)} 
          className="p-1.5 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
        >
          <ChevronRight className="h-4 w-4 lg:h-5 lg:w-5" />
        </button>
      </div>

      <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()}

      <DayTradesModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        selectedDay={selectedDay}
        currentDate={currentDate}
      />
    </Card>
  )
}


UPDATE IT WITH THE FOLLOWING INSTRUCTIONS:
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 AddTradeModal from '@/components/AddTradeModal'

// ... keep all your existing interfaces ...

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 [selectedDay, setSelectedDay] = useState<{
    day: number;
    trades: Trade[];
    stats: DayStats | null;
  } | null>(null)

  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()
      
      // Transform the dates in the response
      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()
  }, [])

  // Add a handler for new trades
  const handleNewTrade = async (newTrade: Trade) => {
    // Update the local state immediately
    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 we have a selected day and the new trade belongs to that day,
    // update the selected day's trades
    if (selectedDay) {
      const newTradeDate = new Date(newTrade.entry_date)
      if (newTradeDate.getDate() === selectedDay.day) {
        const updatedDayTrades = [...selectedDay.trades, newTrade]
        setSelectedDay({
          day: selectedDay.day,
          trades: updatedDayTrades,
          stats: calculateDayStats(updatedDayTrades)
        })
      }
    }
  }

  // ... keep all your existing helper functions and rendering functions ...

  return (
    <Card className="bg-white dark:bg-gray-900 w-[95%] lg:w-[90%] xl:w-[85%] mx-auto">
      {/* ... keep your existing calendar header ... */}

      <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">
            {/* ... keep your existing table header ... */}
            <tbody>
              {renderCalendarGrid()}
            </tbody>
          </table>
        </div>
      </div>

      {renderStatistics()}

      <DayTradesModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        selectedDay={selectedDay}
        currentDate={currentDate}
        onNewTrade={handleNewTrade} {/* Add this prop */}
      />
    </Card>
  )
}