update this code 'use client'

import React from 'react';
import { Card } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { BarChart2, TrendingUp, TrendingDown, DollarSign, ArrowUp, ArrowDown } from "lucide-react";
import { useTheme as useNextTheme } from "next-themes";

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

interface Stats {
  totalTrades: number;
  winRate: string;
  profitFactor: string;
  maxDrawdown: string;
}

type TimeFilter = '7d' | '30d' | '90d' | '180d' | '1y' | 'all';

export default function Dashboard() {
  const { theme, setTheme } = useNextTheme();
  const [mounted, setMounted] = React.useState(false);
  const [trades, setTrades] = React.useState<Trade[]>([]);
  const [allTrades, setAllTrades] = React.useState<Trade[]>([]);
  const [timeFilter, setTimeFilter] = React.useState<TimeFilter>('30d');
  const [stats, setStats] = React.useState<Stats>({
    totalTrades: 0,
    winRate: '0',
    profitFactor: '0',
    maxDrawdown: '0'
  });
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');

  // Calculate date range based on filter
  const getDateRange = (filter: TimeFilter): Date => {
    const now = new Date();
    switch (filter) {
      case '7d':
        return new Date(now.setDate(now.getDate() - 7));
      case '30d':
        return new Date(now.setDate(now.getDate() - 30));
      case '90d':
        return new Date(now.setDate(now.getDate() - 90));
      case '180d':
        return new Date(now.setDate(now.getDate() - 180));
      case '1y':
        return new Date(now.setFullYear(now.getFullYear() - 1));
      case 'all':
        return new Date(0); // Beginning of time
      default:
        return new Date(now.setDate(now.getDate() - 30));
    }
  };

  // Calculate statistics based on filtered trades
  const calculateStats = (filteredTrades: Trade[]): Stats => {
    const winningTrades = filteredTrades.filter(trade => trade.pnl >= 0);
    const losingTrades = filteredTrades.filter(trade => trade.pnl < 0);
    
    const totalWins = winningTrades.reduce((acc, trade) => acc + trade.pnl, 0);
    const totalLosses = Math.abs(losingTrades.reduce((acc, trade) => acc + trade.pnl, 0));
    
    const winRate = (winningTrades.length / filteredTrades.length * 100 || 0).toFixed(1);
    const profitFactor = totalLosses === 0 ? "∞" : (totalWins / totalLosses).toFixed(2);
    
    // Calculate max drawdown
    let maxDrawdown = 0;
    let peak = 0;
    let runningPnL = 0;
    
    filteredTrades.forEach(trade => {
      runningPnL += trade.pnl;
      if (runningPnL > peak) {
        peak = runningPnL;
      }
      const drawdown = ((peak - runningPnL) / peak) * 100;
      if (drawdown > maxDrawdown) {
        maxDrawdown = drawdown;
      }
    });

    return {
      totalTrades: filteredTrades.length,
      winRate,
      profitFactor,
      maxDrawdown: maxDrawdown.toFixed(1)
    };
  };

  // Filter trades based on time range
  const filterTrades = React.useCallback((filter: TimeFilter) => {
    const dateThreshold = getDateRange(filter);
    const filtered = allTrades.filter(trade => 
      new Date(trade.entry_date) >= dateThreshold
    );
    setTrades(filtered);
    setStats(calculateStats(filtered));
  }, [allTrades]);

  // Handle filter change
  const handleFilterChange = (value: TimeFilter) => {
    setTimeFilter(value);
    filterTrades(value);
  };

  React.useEffect(() => {
    async function fetchTrades() {
      try {
        const res = await fetch('/api/trades');
        if (!res.ok) throw new Error('Failed to fetch trades');
        
        const data = await res.json();
        setAllTrades(data.trades);
        filterTrades(timeFilter); // Apply initial filter
      } catch (err) {
        setError('Failed to load trades');
      } finally {
        setLoading(false);
      }
    }

    fetchTrades();
  }, []);

  React.useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) return null;
  if (loading) return (
    <div className="flex items-center justify-center min-h-screen dark:bg-gray-900">
      <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
    </div>
  );
  if (error) return (
    <div className="flex items-center justify-center min-h-screen text-red-500 dark:bg-gray-900">
      <div className="text-center">
        <div className="text-xl font-bold mb-2">Error Loading Data</div>
        <div>{error}</div>
      </div>
    </div>
  );

  return (
    <div className="p-6 space-y-6 dark:bg-gray-900 min-h-screen">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card className="p-6 hover:shadow-lg transition-shadow duration-200 dark:bg-gray-800 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500 dark:text-gray-400">Total Trades</p>
              <p className="text-3xl font-bold mt-2 dark:text-white">{stats.totalTrades}</p>
            </div>
            <div className="bg-blue-100 dark:bg-blue-900/50 p-3 rounded-full">
              <BarChart2 className="h-6 w-6 text-blue-600 dark:text-blue-400" />
            </div>
          </div>
        </Card>

        <Card className="p-6 hover:shadow-lg transition-shadow duration-200 dark:bg-gray-800 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500 dark:text-gray-400">Win Rate</p>
              <p className="text-3xl font-bold mt-2 dark:text-white">{stats.winRate}%</p>
            </div>
            <div className="bg-green-100 dark:bg-green-900/50 p-3 rounded-full">
              <TrendingUp className="h-6 w-6 text-green-600 dark:text-green-400" />
            </div>
          </div>
        </Card>

        <Card className="p-6 hover:shadow-lg transition-shadow duration-200 dark:bg-gray-800 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500 dark:text-gray-400">Profit Factor</p>
              <p className="text-3xl font-bold mt-2 dark:text-white">{stats.profitFactor}</p>
            </div>
            <div className="bg-yellow-100 dark:bg-yellow-900/50 p-3 rounded-full">
              <DollarSign className="h-6 w-6 text-yellow-600 dark:text-yellow-400" />
            </div>
          </div>
        </Card>

        <Card className="p-6 hover:shadow-lg transition-shadow duration-200 dark:bg-gray-800 dark:border-gray-700">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-500 dark:text-gray-400">Max Drawdown</p>
              <p className="text-3xl font-bold mt-2 dark:text-white">{stats.maxDrawdown}%</p>
            </div>
            <div className="bg-red-100 dark:bg-red-900/50 p-3 rounded-full">
              <TrendingDown className="h-6 w-6 text-red-600 dark:text-red-400" />
            </div>
          </div>
        </Card>
      </div>

      <Card className="overflow-hidden dark:bg-gray-800 dark:border-gray-700">
        <div className="p-6 border-b border-gray-100 dark:border-gray-700 flex justify-between items-center">
          <h2 className="text-xl font-bold dark:text-white">Recent Trades</h2>
          <Select value={timeFilter} onValueChange={(value: TimeFilter) => handleFilterChange(value)}>
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="Select time range" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="7d">Last 7 days</SelectItem>
              <SelectItem value="30d">Last 30 days</SelectItem>
              <SelectItem value="90d">Last 90 days</SelectItem>
              <SelectItem value="180d">Last 6 months</SelectItem>
              <SelectItem value="1y">Last year</SelectItem>
              <SelectItem value="all">All time</SelectItem>
            </SelectContent>
          </Select>
        </div>
        
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50 dark:bg-gray-700/50">
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Date</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Symbol</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Type</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Entry</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Exit</th>
                <th className="px-6 py-4 text-left text-sm font-medium text-gray-500 dark:text-gray-400">P/L</th>
              </tr>
            </thead>
            <tbody>
              {trades.map((trade, index) => (
                <tr 
                  key={trade.id}
                  className={`
                    hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors duration-150
                    ${index % 2 === 0 ? 'bg-white dark:bg-gray-800' : 'bg-gray-50/50 dark:bg-gray-700/30'}
                  `}
                >
                  <td className="px-6 py-4 text-sm dark:text-gray-300">
                    {new Date(trade.entry_date).toLocaleDateString()}
                  </td>
                  <td className="px-6 py-4 text-sm font-medium dark:text-gray-200">{trade.symbol}</td>
                  <td className="px-6 py-4">
                    <span className={`
                      px-2 py-1 rounded-full text-xs font-medium
                      ${trade.type === 'LONG' 
                        ? 'bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-400' 
                        : 'bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-400'}
                    `}>
                      {trade.type}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-sm dark:text-gray-300">${trade.entry_price.toFixed(2)}</td>
                  <td className="px-6 py-4 text-sm dark:text-gray-300">${trade.exit_price.toFixed(2)}</td>
                  <td className="px-6 py-4">
                    <div className={`
                      flex items-center space-x-1
                      ${trade.pnl >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}
                    `}>
                      {trade.pnl >= 0 ? 
                        <ArrowUp className="h-4 w-4" /> : 
                        <ArrowDown className="h-4 w-4" />
                      }
                      <span className="font-medium">
                        {Math.abs(trade.pnl_percent).toFixed(2)}%
                      </span>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

with these indications:'use client'

import React from 'react';
import { Card } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { BarChart2, TrendingUp, TrendingDown, DollarSign, ArrowUp, ArrowDown } from "lucide-react";
import { useTheme } from "next-themes";

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

interface Stats {
  totalTrades: number;
  winRate: string;
  profitFactor: string;
  maxDrawdown: string;
}

type TimeFilter = '7d' | '30d' | '90d' | '180d' | '1y' | 'all';

export default function Dashboard() {
  const { theme } = useTheme();
  const [mounted, setMounted] = React.useState(false);
  const [trades, setTrades] = React.useState<Trade[]>([]);
  const [allTrades, setAllTrades] = React.useState<Trade[]>([]);
  const [timeFilter, setTimeFilter] = React.useState<TimeFilter>('30d'); // Set default to 30d
  const [stats, setStats] = React.useState<Stats>({
    totalTrades: 0,
    winRate: '0',
    profitFactor: '0',
    maxDrawdown: '0'
  });
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');

  // Calculate date range based on filter
  const getDateRange = (filter: TimeFilter): Date => {
    const now = new Date();
    switch (filter) {
      case '7d':
        return new Date(now.setDate(now.getDate() - 7));
      case '30d':
        return new Date(now.setDate(now.getDate() - 30));
      case '90d':
        return new Date(now.setDate(now.getDate() - 90));
      case '180d':
        return new Date(now.setDate(now.getDate() - 180));
      case '1y':
        return new Date(now.setFullYear(now.getFullYear() - 1));
      case 'all':
        return new Date(0);
      default:
        return new Date(now.setDate(now.getDate() - 30));
    }
  };

  // Calculate statistics based on filtered trades
  const calculateStats = (filteredTrades: Trade[]): Stats => {
    if (!filteredTrades.length) {
      return {
        totalTrades: 0,
        winRate: '0',
        profitFactor: '0',
        maxDrawdown: '0'
      };
    }

    const winningTrades = filteredTrades.filter(trade => trade.pnl >= 0);
    const losingTrades = filteredTrades.filter(trade => trade.pnl < 0);
    
    const totalWins = winningTrades.reduce((acc, trade) => acc + trade.pnl, 0);
    const totalLosses = Math.abs(losingTrades.reduce((acc, trade) => acc + trade.pnl, 0));
    
    const winRate = (winningTrades.length / filteredTrades.length * 100 || 0).toFixed(1);
    const profitFactor = totalLosses === 0 ? "∞" : (totalWins / totalLosses).toFixed(2);
    
    let maxDrawdown = 0;
    let peak = 0;
    let runningPnL = 0;
    
    filteredTrades.forEach(trade => {
      runningPnL += trade.pnl;
      if (runningPnL > peak) {
        peak = runningPnL;
      }
      const drawdown = peak > 0 ? ((peak - runningPnL) / peak) * 100 : 0;
      if (drawdown > maxDrawdown) {
        maxDrawdown = drawdown;
      }
    });

    return {
      totalTrades: filteredTrades.length,
      winRate,
      profitFactor,
      maxDrawdown: maxDrawdown.toFixed(1)
    };
  };

  // Filter trades based on time range
  const filterTrades = React.useCallback((filter: TimeFilter, tradesData: Trade[]) => {
    const dateThreshold = getDateRange(filter);
    const filtered = tradesData.filter(trade => 
      new Date(trade.entry_date) >= dateThreshold
    );
    setTrades(filtered);
    setStats(calculateStats(filtered));
  }, []);

  // Handle filter change
  const handleFilterChange = (value: TimeFilter) => {
    setTimeFilter(value);
    filterTrades(value, allTrades);
  };

  // Fetch and set initial data
  React.useEffect(() => {
    async function fetchTrades() {
      try {
        const res = await fetch('/api/trades');
        if (!res.ok) throw new Error('Failed to fetch trades');
        
        const data = await res.json();
        setAllTrades(data.trades);
        // Immediately filter trades for default 30d view
        filterTrades('30d', data.trades);
      } catch (err) {
        setError('Failed to load trades');
      } finally {
        setLoading(false);
      }
    }

    fetchTrades();
  }, []); // Empty dependency array to run only once

  React.useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) return null;

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

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen dark:bg-gray-900">
        <div className="text-center text-red-500 dark:text-red-400">
          <p className="text-xl font-bold">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6 dark:bg-gray-900">
      {/* Rest of your JSX remains the same */}
    </div>
  );
}

return me only the updated code