'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";

// Updated Trade interface to match API response
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];

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

  // Helper function to format currency
  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD'
    }).format(value);
  };

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

        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();
  }, []);

  // Debug log when selectedTrade changes
  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 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">
        <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-4">
            <div className="space-y-4">
              {entries.map(entry => (
                <Card 
                  key={entry.date}
                  className={`p-4 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors
                    ${selectedDate === entry.date ? 'border-blue-500 dark:border-blue-400' : ''}`}
                  onClick={() => {
                    setSelectedDate(entry.date);
                    setSelectedTradeIndex(0);
                  }}
                >
                  <div className="font-medium">
                    {new Date(entry.date).toLocaleDateString('en-US', {
                      weekday: 'short',
                      year: 'numeric',
                      month: 'short',
                      day: 'numeric'
                    })}
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">
                    {entry.trades.length} trade{entry.trades.length !== 1 ? 's' : ''}
                  </div>
                  <div className="mt-2 text-sm">
                    {entry.trades.map(trade => (
                      <div 
                        key={trade.id}
                        className={`flex justify-between items-center
                          ${trade.pnl_percent >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}`}
                      >
                        <span>{trade.symbol}</span>
                        <span>{trade.pnl_percent >= 0 ? '+' : ''}{trade.pnl_percent.toFixed(2)}%</span>
                      </div>
                    ))}
                  </div>
                </Card>
              ))}
            </div>
          </div>

          <div className="col-span-8">
            <Card className="p-6">
              <div className="space-y-6">
                <div className="flex justify-between items-center">
                  <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="space-y-4">
                    {/* Trade Image */}
                    <div className="h-32">
                      <Card className="h-full overflow-hidden">
                        <img 
                          src="/api/placeholder/400/128" 
                          alt="Trade Chart" 
                          className="w-full h-full object-cover"
                        />
                      </Card>
                    </div>

                    {/* Primary Stats Row */}
                    <div className="flex gap-4">
                      <Card className="flex-1 p-3 bg-gray-50 dark:bg-gray-800">
                        <div className="text-sm text-gray-500">Type</div>
                        <div className="font-medium">{selectedTrade.type}</div>
                      </Card>
                      <Card className="flex-1 p-3 bg-gray-50 dark:bg-gray-800">
                        <div className="text-sm text-gray-500">P/L %</div>
                        <div className={`font-medium ${selectedTrade.pnl_percent >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                          {selectedTrade.pnl_percent >= 0 ? '+' : ''}{selectedTrade.pnl_percent.toFixed(2)}%
                        </div>
                      </Card>
                    </div>

                    {/* Secondary Stats Row */}
                    <div className="flex gap-4">
                      <Card className="flex-1 p-3 bg-gray-50 dark:bg-gray-800">
                        <div className="text-sm text-gray-500">P/L $</div>
                        <div className={`font-medium ${selectedTrade.pnl >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                          {formatCurrency(selectedTrade.pnl)}
                        </div>
                      </Card>
                      <Card className="flex-1 p-3 bg-gray-50 dark:bg-gray-800">
                        <div className="text-sm text-gray-500">Size</div>
                        <div className="font-medium">
                          {typeof selectedTrade.quantity !== 'undefined' ? formatQuantity(selectedTrade.quantity) : 'N/A'}
                        </div>
                      </Card>
                    </div>

                    {/* Notes Section */}
                    <div>
                      <div className="flex justify-between items-center mb-2">
                        <h4 className="font-medium">Notes for {selectedTrade.symbol}</h4>
                        <Button onClick={handleSaveNote}>
                          <SaveIcon className="h-4 w-4 mr-2" />
                          Save Notes
                        </Button>
                      </div>
                      <Textarea
                        className="min-h-[200px] resize-none"
                        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 the following instrructions:
'use client'

// ... (previous imports remain the same)

export default function TradingJournal() {
  // ... (previous state and functions remain the same until the render part)

  // Add new function to calculate daily totals
  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 });
  };

  return (
    <div className="space-y-6">
      <Card className="p-6">
        {/* ... (previous header section remains the same) */}

        <div className="grid grid-cols-12 gap-6">
          {/* Reduced width trade list with custom scrollbar */}
          <div className="col-span-3"> {/* Changed from col-span-4 to col-span-3 */}
            <div className="space-y-4 h-[calc(100vh-250px)] overflow-y-auto pr-2 custom-scrollbar">
              {entries.map(entry => {
                const dailyTotals = calculateDailyTotals(entry.trades);
                
                return (
                  <Card 
                    key={entry.date}
                    className={`p-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors
                      ${selectedDate === entry.date ? 'border-blue-500 dark:border-blue-400' : ''}`}
                    onClick={() => {
                      setSelectedDate(entry.date);
                      setSelectedTradeIndex(0);
                    }}
                  >
                    <div className="font-medium text-sm">
                      {new Date(entry.date).toLocaleDateString('en-US', {
                        weekday: 'short',
                        month: 'short',
                        day: 'numeric'
                      })}
                    </div>
                    <div className="text-xs text-gray-500 dark:text-gray-400">
                      {entry.trades.length} trade{entry.trades.length !== 1 ? 's' : ''}
                    </div>
                    
                    {/* Daily total P/L */}
                    <div className={`text-sm font-medium mt-1 ${dailyTotals.totalPnl >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}`}>
                      Daily: {dailyTotals.totalPnl >= 0 ? '+' : ''}{dailyTotals.totalPnlPercent.toFixed(2)}%
                    </div>
                    
                    {/* Individual trades */}
                    <div className="mt-1 text-xs space-y-1">
                      {entry.trades.map(trade => (
                        <div 
                          key={trade.id}
                          className={`flex justify-between items-center
                            ${trade.pnl_percent >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}`}
                        >
                          <span>{trade.symbol}</span>
                          <span>{trade.pnl_percent >= 0 ? '+' : ''}{trade.pnl_percent.toFixed(2)}%</span>
                        </div>
                      ))}
                    </div>
                  </Card>
                );
              })}
            </div>
          </div>

          {/* Increased width for trade details */}
          <div className="col-span-9"> {/* Changed from col-span-8 to col-span-9 */}
            {/* ... (rest of the trade details section remains the same) */}
          </div>
        </div>
      </Card>
    </div>
  );
}

// Add this to your global CSS file (e.g., globals.css)
const styles = `
.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.5);
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: rgba(156, 163, 175, 0.8);
}

.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: rgba(156, 163, 175, 0.5) transparent;
}
`;

return the code updated without comments