take trhe following code:'use client'

import React from 'react';
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { SaveIcon, ChevronLeft, ChevronRight } from "lucide-react";

interface Trade {
  id: number;
  symbol: string;
  type: string;
  entry_price: number;
  exit_price: number;
  quantity: number;
  entry_date: string;
  exit_date: string;
  pnl: number;
  pnl_percent: number;
  notes?: string;
}

interface JournalEntry {
  id: number;
  date: string;
  content: string;
  mood?: string;
  market_notes?: string;
  trades: Trade[];
}

export default function TradingJournal() {
  const [entries, setEntries] = React.useState<JournalEntry[]>([]);
  const [selectedDate, setSelectedDate] = React.useState<string>('');
  const [selectedTradeIndex, setSelectedTradeIndex] = React.useState(0);
  const [tradeNote, setTradeNote] = React.useState('');
  const [loading, setLoading] = React.useState(true);

  const selectedEntry = entries.find(e => e.date === selectedDate);
  const selectedTrade = selectedEntry?.trades[selectedTradeIndex];

  const formatQuantity = (quantity: number) => {
    return quantity?.toLocaleString() || 'N/A';
  };

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(value);
  };

  React.useEffect(() => {
    async function fetchJournalData() {
      try {
        const response = await fetch('/api/journal');
        const data = await response.json();
        console.log('API Response:', data);

        if (data.journalEntries) {
          setEntries(data.journalEntries);
          if (data.journalEntries.length > 0) {
            setSelectedDate(data.journalEntries[0].date);
            setSelectedTradeIndex(0);
            setTradeNote(data.journalEntries[0].trades[0]?.notes || '');
          }
        }
      } catch (error) {
        console.error('Failed to fetch journal data:', error);
      } finally {
        setLoading(false);
      }
    }

    fetchJournalData();
  }, []);

  React.useEffect(() => {
    if (selectedTrade) {
      console.log('Selected Trade:', selectedTrade);
      setTradeNote(selectedTrade.notes || '');
    }
  }, [selectedTradeIndex, selectedDate, selectedTrade]);

  const handleSaveNote = async () => {
    if (!selectedTrade) return;

    try {
      const response = await fetch('/api/trades/notes', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          tradeId: selectedTrade.id,
          notes: tradeNote
        }),
      });

      if (!response.ok) {
        throw new Error(`Error ${response.status}: ${response.statusText}`);
      }

      setEntries(entries.map(entry =>
        entry.date === selectedDate
          ? {
            ...entry,
            trades: entry.trades.map((trade, index) =>
              index === selectedTradeIndex
                ? { ...trade, notes: tradeNote }
                : trade
            )
          }
          : entry
      ));
    } catch (error) {
      console.error('Failed to save note:', error);
    }
  };

  const calculateDailyTotals = (trades: Trade[]) => {
    return trades.reduce((acc, trade) => {
      return {
        totalPnl: acc.totalPnl + trade.pnl,
        totalPnlPercent: acc.totalPnlPercent + trade.pnl_percent,
      };
    }, { totalPnl: 0, totalPnlPercent: 0 });
  };

  const renderTradeNavigation = () => {
    if (!selectedEntry?.trades || selectedEntry.trades.length <= 1) {
      return null;
    }

    return (
      <div className="flex items-center gap-2">
        <Button
          variant="outline"
          size="sm"
          onClick={() => setSelectedTradeIndex(i => Math.max(0, i - 1))}
          disabled={selectedTradeIndex === 0}
        >
          <ChevronLeft className="h-4 w-4" />
        </Button>
        <span className="font-medium">
          {selectedTrade?.symbol} ({selectedTradeIndex + 1}/{selectedEntry.trades.length})
        </span>
        <Button
          variant="outline"
          size="sm"
          onClick={() => setSelectedTradeIndex(i =>
            Math.min((selectedEntry.trades.length || 1) - 1, i + 1)
          )}
          disabled={selectedTradeIndex === (selectedEntry.trades.length - 1)}
        >
          <ChevronRight className="h-4 w-4" />
        </Button>
      </div>
    );
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Card className="p-6">
        {/* Header with title and navigation */}
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold">Trading Journal</h2>
          <div className="flex space-x-4">
            <Button
              variant="outline"
              onClick={() => {
                const currentIndex = entries.findIndex(e => e.date === selectedDate);
                if (currentIndex > 0) {
                  setSelectedDate(entries[currentIndex - 1].date);
                  setSelectedTradeIndex(0);
                }
              }}
            >
              <ChevronLeft className="h-4 w-4" />
              Previous Day
            </Button>
            <Button
              variant="outline"
              onClick={() => {
                const currentIndex = entries.findIndex(e => e.date === selectedDate);
                if (currentIndex < entries.length - 1) {
                  setSelectedDate(entries[currentIndex + 1].date);
                  setSelectedTradeIndex(0);
                }
              }}
            >
              Next Day
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>

        <div className="grid grid-cols-12 gap-6">
          {/* Replace the dates sidebar section with the updated sidebar */}
          <div className="col-span-3">
            <div className="trade-dates-container">
              <div className="trade-dates-scroll">
                {entries.map(entry => {
                  const dailyTotals = calculateDailyTotals(entry.trades);

                  return (
                    <Card
                      key={entry.date}
                      className={`mb-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors w-full truncate
                        ${selectedDate === entry.date ? 'border-primary bg-accent' : ''}`}
                      onClick={() => {
                        setSelectedDate(entry.date);
                        setSelectedTradeIndex(0);
                      }}
                    >
                      <div className="flex justify-between items-start">
                        <div className="min-w-0 flex-shrink">
                          <div className="font-medium text-sm truncate">
                            {new Date(entry.date).toLocaleDateString('en-US', {
                              weekday: 'short',
                              month: 'short',
                              day: 'numeric'
                            })}
                          </div>
                          <div className="text-xs text-muted-foreground mt-0.5">
                            {entry.trades.length} trade{entry.trades.length !== 1 ? 's' : ''}
                          </div>
                        </div>

                        <div className="flex flex-col items-end flex-shrink-0">
                          <div className={`text-sm font-medium ${dailyTotals.totalPnl >= 0 ? 'text-green-500 dark:text-green-400' : 'text-red-500 dark:text-red-400'}`}>
                            {formatCurrency(dailyTotals.totalPnl)}
                          </div>
                          <div className={`text-xs font-medium ${dailyTotals.totalPnlPercent >= 0 ? 'text-green-500 dark:text-green-400' : 'text-red-500 dark:text-red-400'}`}>
                            {dailyTotals.totalPnlPercent >= 0 ? '+' : ''}{dailyTotals.totalPnlPercent.toFixed(2)}%
                          </div>
                        </div>
                      </div>
                    </Card>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Right side - Trade details */}
          <div className="col-span-9">
            <Card className="p-6">
              <div className="flex flex-col h-[calc(100vh-220px)]">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-lg font-medium">
                    {selectedDate ? new Date(selectedDate).toLocaleDateString('en-US', {
                      weekday: 'long',
                      year: 'numeric',
                      month: 'long',
                      day: 'numeric'
                    }) : 'Select a date'}
                  </h3>
                  {renderTradeNavigation()}
                </div>

                {selectedTrade && (
                  <div className="flex flex-col flex-grow overflow-hidden space-y-4">
                    <div className="flex gap-6">
                      <div className="w-3/4">
                        <div className="grid grid-cols-4 gap-2"> {/* Changed from grid-cols-2 and gap-4 to grid-cols-4 and gap-2 */}
                          <Card className="p-2 bg-slate-800/40"> {/* Changed from p-3 */}
                            <div className="text-xs text-slate-400 mb-0.5 uppercase tracking-wider">Type</div>
                            <div className="font-medium text-base">{selectedTrade.type}</div> {/* Changed from text-lg */}
                          </Card>
                          <Card className="p-2 bg-slate-800/40">
                            <div className="text-xs text-slate-400 mb-0.5 uppercase tracking-wider">P/L %</div>
                            <div className={`font-medium text-base ${selectedTrade.pnl_percent >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
                              {selectedTrade.pnl_percent >= 0 ? '+' : ''}{selectedTrade.pnl_percent.toFixed(2)}%
                            </div>
                          </Card>
                          <Card className="p-2 bg-slate-800/40">
                            <div className="text-xs text-slate-400 mb-0.5 uppercase tracking-wider">P/L $</div>
                            <div className={`font-medium text-base ${selectedTrade.pnl >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
                              {formatCurrency(selectedTrade.pnl)}
                            </div>
                          </Card>
                          <Card className="p-2 bg-slate-800/40">
                            <div className="text-xs text-slate-400 mb-0.5 uppercase tracking-wider">Size</div>
                            <div className="font-medium text-base">
                              {typeof selectedTrade.quantity !== 'undefined' ? formatQuantity(selectedTrade.quantity) : 'N/A'}
                            </div>
                          </Card>
                        </div>
                      </div>

                      <div className="w-1/4">
                        <Card className="h-full overflow-hidden bg-slate-800 border-slate-700">
                          <img
                            src="/api/placeholder/400/128"
                            alt="Trade Chart"
                            className="w-full h-full object-cover"
                          />
                        </Card>
                      </div>
                    </div>

                    <div className="flex-grow flex flex-col">
                      <div className="flex justify-between items-center mb-2">
                        <h4 className="font-medium text-lg text-slate-200">Notes for {selectedTrade.symbol}</h4>
                        <Button
                          onClick={handleSaveNote}
                          className="bg-slate-700 hover:bg-slate-600"
                        >
                          <SaveIcon className="h-4 w-4 mr-2" />
                          Save Notes
                        </Button>
                      </div>
                      <Textarea
                        className="flex-grow resize-none min-h-[300px] bg-slate-800 border-slate-700 text-slate-200"
                        placeholder="Write your notes for this trade..."
                        value={tradeNote}
                        onChange={(e) => setTradeNote(e.target.value)}
                      />
                    </div>
                  </div>
                )}
              </div>
            </Card>
          </div>
        </div>
      </Card>
    </div>
  );
}



update this code following these instructions:'use client'

import React from 'react';
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { SaveIcon, ChevronLeft, ChevronRight } from "lucide-react";

// ... keep all interfaces the same ...

export default function TradingJournal() {
  // ... keep all state and functions the same until the return statement ...

  return (
    <div className="space-y-6">
      <Card className="p-6">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold">Trading Journal</h2>
          <div className="flex space-x-4">
            <Button 
              variant="outline"
              onClick={() => {
                const currentIndex = entries.findIndex(e => e.date === selectedDate);
                if (currentIndex > 0) {
                  setSelectedDate(entries[currentIndex - 1].date);
                  setSelectedTradeIndex(0);
                }
              }}
            >
              <ChevronLeft className="h-4 w-4" />
              Previous Day
            </Button>
            <Button 
              variant="outline"
              onClick={() => {
                const currentIndex = entries.findIndex(e => e.date === selectedDate);
                if (currentIndex < entries.length - 1) {
                  setSelectedDate(entries[currentIndex + 1].date);
                  setSelectedTradeIndex(0);
                }
              }}
            >
              Next Day
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>

        <div className="grid grid-cols-12 gap-6">
          <div className="col-span-3">
            <div className="relative pl-1.5">
              <div 
                className="absolute left-0 top-0 bottom-0 w-1.5 bg-slate-700/20 opacity-0 transition-opacity duration-200"
                style={{ opacity: 0 }}
              />
              <div className="h-[calc(100vh-220px)] overflow-y-scroll scrollbar-left">
                {entries.map(entry => {
                  const dailyTotals = calculateDailyTotals(entry.trades);
                  
                  return (
                    <Card 
                      key={entry.date}
                      className={`mb-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors w-full truncate
                        ${selectedDate === entry.date ? 'border-primary bg-accent' : ''}`}
                      onClick={() => {
                        setSelectedDate(entry.date);
                        setSelectedTradeIndex(0);
                      }}
                    >
                      <div className="flex justify-between items-start">
                        <div className="min-w-0 flex-shrink">
                          <div className="font-medium text-sm truncate">
                            {new Date(entry.date).toLocaleDateString('en-US', {
                              weekday: 'short',
                              month: 'short',
                              day: 'numeric'
                            })}
                          </div>
                          <div className="text-xs text-muted-foreground mt-0.5">
                            {entry.trades.length} trade{entry.trades.length !== 1 ? 's' : ''}
                          </div>
                        </div>
                        
                        <div className="flex flex-col items-end flex-shrink-0">
                          <div className={`text-sm font-medium ${dailyTotals.totalPnl >= 0 ? 'text-green-500 dark:text-green-400' : 'text-red-500 dark:text-red-400'}`}>
                            {formatCurrency(dailyTotals.totalPnl)}
                          </div>
                          <div className={`text-xs font-medium ${dailyTotals.totalPnlPercent >= 0 ? 'text-green-500 dark:text-green-400' : 'text-red-500 dark:text-red-400'}`}>
                            {dailyTotals.totalPnlPercent >= 0 ? '+' : ''}{dailyTotals.totalPnlPercent.toFixed(2)}%
                          </div>
                        </div>
                      </div>
                    </Card>
                  );
                })}
              </div>
            </div>
          </div>

          <div className="col-span-9">
            <Card className="p-6">
              <div className="flex flex-col h-[calc(100vh-220px)]">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-lg font-medium">
                    {selectedDate ? new Date(selectedDate).toLocaleDateString('en-US', {
                      weekday: 'long',
                      year: 'numeric',
                      month: 'long',
                      day: 'numeric'
                    }) : 'Select a date'}
                  </h3>
                  {renderTradeNavigation()}
                </div>

                {selectedTrade && (
                  <div className="flex flex-col flex-grow overflow-hidden space-y-4">
                    <div className="flex gap-6">
                      <div className="w-3/4">
                        <div className="grid grid-cols-4 gap-2">
                          <Card className="p-2 bg-slate-800/40">
                            <div className="text-xs text-slate-400 mb-0.5 uppercase tracking-wider">Type</div>
                            <div className="font-medium text-base">{selectedTrade.type}</div>
                          </Card>
                          <Card className="p-2 bg-slate-800/40">
                            <div className="text-xs text-slate-400 mb-0.5 uppercase tracking-wider">P/L %</div>
                            <div className={`font-medium text-base ${selectedTrade.pnl_percent >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
                              {selectedTrade.pnl_percent >= 0 ? '+' : ''}{selectedTrade.pnl_percent.toFixed(2)}%
                            </div>
                          </Card>
                          <Card className="p-2 bg-slate-800/40">
                            <div className="text-xs text-slate-400 mb-0.5 uppercase tracking-wider">P/L $</div>
                            <div className={`font-medium text-base ${selectedTrade.pnl >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
                              {formatCurrency(selectedTrade.pnl)}
                            </div>
                          </Card>
                          <Card className="p-2 bg-slate-800/40">
                            <div className="text-xs text-slate-400 mb-0.5 uppercase tracking-wider">Size</div>
                            <div className="font-medium text-base">
                              {typeof selectedTrade.quantity !== 'undefined' ? formatQuantity(selectedTrade.quantity) : 'N/A'}
                            </div>
                          </Card>
                        </div>
                      </div>

                      <div className="w-1/4">
                        <Card className="h-full overflow-hidden bg-slate-800 border-slate-700">
                          <img 
                            src="/api/placeholder/400/128" 
                            alt="Trade Chart" 
                            className="w-full h-full object-cover"
                          />
                        </Card>
                      </div>
                    </div>

                    <div className="flex-grow flex flex-col">
                      <div className="flex justify-between items-center mb-2">
                        <h4 className="font-medium text-lg text-slate-200">Notes for {selectedTrade.symbol}</h4>
                        <Button 
                          onClick={handleSaveNote}
                          className="bg-slate-700 hover:bg-slate-600"
                        >
                          <SaveIcon className="h-4 w-4 mr-2" />
                          Save Notes
                        </Button>
                      </div>
                      <Textarea
                        className="flex-grow resize-none min-h-[300px] bg-slate-800 border-slate-700 text-slate-200"
                        placeholder="Write your notes for this trade..."
                        value={tradeNote}
                        onChange={(e) => setTradeNote(e.target.value)}
                      />
                    </div>
                  </div>
                )}
              </div>
            </Card>
          </div>
        </div>
      </Card>
    </div>
  );
}