this is the 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'
import AddTradeModal from '@/components/AddTradeModal' // New Import

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)
  const [isAddTradeModalOpen, setIsAddTradeModalOpen] = useState(false) // State for AddTradeModal

  // Fetch Trades Function Moved Outside useEffect
  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()
  }, [])

  // 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 &&
        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, // 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" key={`empty-${Math.random()}`}>
          <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}
        onNewTrade={handleNewTrade}
      />

      {/* AddTradeModal Integration */}
      <AddTradeModal
        isOpen={isAddTradeModalOpen}
        onClose={() => setIsAddTradeModalOpen(false)}
        onAddTrade={handleNewTrade}
        currentDate={currentDate}
      />

      {/* Optional: Button to Open AddTradeModal */}
      <button
        onClick={() => setIsAddTradeModalOpen(true)}
        className="fixed bottom-6 right-6 bg-blue-600 text-white p-4 rounded-full shadow-lg hover:bg-blue-700 transition-colors"
      >
        +
      </button>
    </Card>
  )
}

update it with the instructions: and only give back the fullcode
import { useState } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { useToast } from "@/components/ui/use-toast"
import { Plus } from "lucide-react"
import { Trade } from '@/types/trade'

interface AddTradeModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAddTrade: (trade: Trade) => void;
  currentDate: Date;
}

interface TradeFormData {
  symbol: string
  type: 'LONG' | 'SHORT'
  entry_price: string
  exit_price: string
  quantity: string
  entry_date: string
  exit_date: string
  notes: string
}

export default function AddTradeModal({ isOpen, onClose, onAddTrade, currentDate }: AddTradeModalProps) {
  const { toast } = useToast()
  const [loading, setLoading] = useState(false)
  
  const [tradeData, setTradeData] = useState<TradeFormData>({
    symbol: '',
    type: 'LONG',
    entry_price: '',
    exit_price: '',
    quantity: '',
    entry_date: '',
    exit_date: '',
    notes: ''
  })

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setLoading(true)

    try {
      const payload = {
        ...tradeData,
        entry_price: parseFloat(tradeData.entry_price),
        exit_price: parseFloat(tradeData.exit_price),
        quantity: parseFloat(tradeData.quantity),
      }

      const res = await fetch('/api/trades', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      })

      if (!res.ok) {
        const error = await res.json()
        throw new Error(error.message || 'Failed to add trade')
      }

      const newTrade = await res.json()
      onAddTrade(newTrade)

      toast({
        title: "Success",
        description: "Trade added successfully"
      })

      onClose() // Close the modal using the provided onClose prop
      
      // Reset form
      setTradeData({
        symbol: '',
        type: 'LONG',
        entry_price: '',
        exit_price: '',
        quantity: '',
        entry_date: '',
        exit_date: '',
        notes: ''
      })
    } catch (error: any) {
      toast({
        title: "Error",
        description: error.message || "Failed to add trade",
        variant: "destructive"
      })
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>Add New Trade</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="symbol">Symbol</Label>
              <Input
                id="symbol"
                value={tradeData.symbol}
                onChange={(e) => setTradeData({ ...tradeData, symbol: e.target.value.toUpperCase() })}
                placeholder="AAPL"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="type">Type</Label>
              <Select
                value={tradeData.type}
                onValueChange={(value: 'LONG' | 'SHORT') => setTradeData({ ...tradeData, type: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select type" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="LONG">Long</SelectItem>
                  <SelectItem value="SHORT">Short</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="entry_price">Entry Price</Label>
              <Input
                id="entry_price"
                type="number"
                step="0.01"
                value={tradeData.entry_price}
                onChange={(e) => setTradeData({ ...tradeData, entry_price: e.target.value })}
                placeholder="100.00"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="exit_price">Exit Price</Label>
              <Input
                id="exit_price"
                type="number"
                step="0.01"
                value={tradeData.exit_price}
                onChange={(e) => setTradeData({ ...tradeData, exit_price: e.target.value })}
                placeholder="110.00"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="quantity">Quantity</Label>
              <Input
                id="quantity"
                type="number"
                step="0.01"
                value={tradeData.quantity}
                onChange={(e) => setTradeData({ ...tradeData, quantity: e.target.value })}
                placeholder="100"
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="entry_date">Entry Date</Label>
              <Input
                id="entry_date"
                type="datetime-local"
                value={tradeData.entry_date}
                onChange={(e) => setTradeData({ ...tradeData, entry_date: e.target.value })}
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="exit_date">Exit Date</Label>
              <Input
                id="exit_date"
                type="datetime-local"
                value={tradeData.exit_date}
                onChange={(e) => setTradeData({ ...tradeData, exit_date: e.target.value })}
                required
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="notes">Notes</Label>
            <Textarea
              id="notes"
              value={tradeData.notes}
              onChange={(e) => setTradeData({ ...tradeData, notes: e.target.value })}
              placeholder="Add your trade notes here..."
              className="min-h-[100px]"
            />
          </div>

          <div className="flex justify-end space-x-4">
            <Button
              type="button"
              variant="outline"
              onClick={onClose}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={loading}>
              {loading ? 'Adding...' : 'Add Trade'}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  )
}