'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_date: string;
  entry_price: number;
  exit_price: number;
  quantity: number;
  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];

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

  React.useEffect(() => {
    async function fetchJournalData() {
      try {
        const response = await fetch('/api/journal');
        const data = await response.json();
        
        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) {
      setTradeNote(selectedTrade.notes || '');
    }
  }, [selectedTradeIndex, selectedDate]);

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

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

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

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

  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'}`}>
          ${selectedTrade.pnl.toFixed(2)}
        </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">
          {selectedrade.quantity}
        </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>
  );
}

you have this code and you must update all of it following the instructions that ig ive you now:{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'}`}>
          ${selectedTrade.pnl.toFixed(2)}
        </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">
          {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>
)}

give me the full updated code