// src/components/DayTradesModal.tsx
'use client';

import React from 'react';
import { Button } from "@/components/ui/button";
import { BookText } from "lucide-react";
import AddTradeModal from './AddTradeModal';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from 'recharts';
import { Trade, DayStats } from '@/types/trade';

interface ChartDataPoint {
  name: string;
  value: number;
}

interface DayTradesModalProps {
  isOpen: boolean;
  onClose: () => void;
  selectedDay: {
    day: number;
    trades: Trade[];
    stats: DayStats | null;
  } | null;
  currentDate: Date;
  onNewTrade: (newTrade: Trade) => void; // Added prop
}

const calculateY2 = (value: number) => {
  return (value - 25) / 1.25;
};

const CustomTooltip = ({ active, payload }: any) => {
  if (active && payload && payload.length) {
    const isNegative = payload[0].value < 0;
    return (
      <div className="bg-white dark:bg-gray-800 p-2 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg">
        <p className="text-sm font-medium">{payload[0].payload.name}</p>
        <p className={`text-sm font-semibold ${isNegative ? 'text-red-600' : 'text-green-600'}`}>
          ${payload[0].value.toFixed(2)}
        </p>
      </div>
    );
  }
  return null;
};

export const DayTradesModal: React.FC<DayTradesModalProps> = ({
  isOpen,
  onClose,
  selectedDay,
  currentDate,
  onNewTrade, // Destructure the new prop
}) => {
  if (!selectedDay) return null;

  const sortedTrades = [...selectedDay.trades].sort(
    (a, b) => new Date(a.exit_date).getTime() - new Date(b.exit_date).getTime()
  );

  const chartData: ChartDataPoint[] = [{ name: 'Start', value: 0 }];
  let runningTotal = 0;
  sortedTrades.forEach((trade, index) => {
    runningTotal += trade.pnl;
    chartData.push({
      name: `Trade ${index + 1}`,
      value: runningTotal,
    });
  });

  const values = chartData.map((point) => point.value);
  const minY = Math.min(...values);
  const maxY = Math.max(...values);
  const padding = Math.abs(maxY - minY) * 0.1;
  const yMin = minY - padding;
  const yMax = maxY + padding;

  const zeroLinePercent = ((0 - yMin) / (yMax - yMin) * 100).toFixed(2);
  const zeroLineY = ((yMax - 0) / (yMax - yMin)) * 300;
  const gradientY2 = calculateY2(zeroLineY);

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

  const formatQuantity = (value: number) => {
    return new Intl.NumberFormat('en-US').format(value);
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[950px] max-h-[90vh] flex flex-col p-0">
        <div className="fixed-section border-b dark:border-gray-700">
          <DialogHeader className="p-6 pb-2">
            <div className="flex items-center justify-between">
              <div>
                <DialogTitle>Trading Activity</DialogTitle>
                <DialogDescription>
                  Summary for {currentDate.toLocaleDateString()}
                </DialogDescription>
              </div>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="icon"
                  onClick={() => {
                    console.log("Open notes");
                  }}
                >
                  <BookText className="h-4 w-4" />
                </Button>
                <AddTradeModal onTradeAdded={onNewTrade} /> {/* Passed the new prop */}
              </div>
            </div>
          </DialogHeader>

          <div className="px-6 pb-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                <p className="text-sm text-gray-500">Net P&L</p>
                <p className={`text-2xl font-bold ${selectedDay.stats?.pnl !== undefined && selectedDay.stats.pnl >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                  {formatCurrency(selectedDay.stats?.pnl || 0)}
                </p>
              </div>
              <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                <p className="text-sm text-gray-500">Win Rate</p>
                <p className="text-2xl font-bold">{selectedDay.stats?.winRatePercent.toFixed(1)}%</p>
              </div>
              <div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
                <p className="text-sm text-gray-500">Total Trades</p>
                <p className="text-2xl font-bold">{selectedDay.trades.length}</p>
              </div>
            </div>
          </div>
        </div>

        <div 
          className="flex-1 overflow-y-scroll scrollbar-content"
          style={{
            marginTop: '190px',
            padding: '25px 46px 30px 55px',
          }}
        >
          <div className="mb-6">
            <div className="w-full h-[300px] bg-gray-800/50 dark:bg-gray-900 rounded-lg">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart
                  data={chartData}
                  margin={{ top: 20, right: 30, left: -25, bottom: 5 }}
                >
                  <defs>
                    <linearGradient 
                      id="splitColor"
                      x1="0" 
                      y1="0" 
                      x2="0" 
                      y2={`${gradientY2}%`}
                    >
                      <stop offset="0%" stopColor="rgb(132, 204, 171)" stopOpacity={0.8} />
                      <stop offset="50%" stopColor="rgb(132, 204, 171)" stopOpacity={0.2} />
                      <stop offset="50%" stopColor="rgb(255, 160, 160)" stopOpacity={0.2} />
                      <stop offset="100%" stopColor="rgb(255, 160, 160)" stopOpacity={0.8} />
                    </linearGradient>
                    <linearGradient 
                      id="strokeColor" 
                      x1="0" 
                      y1="0" 
                      x2="0" 
                      y2={`${gradientY2}%`}
                    >
                      <stop offset="50%" stopColor="rgb(34, 197, 94)" />
                      <stop offset="50%" stopColor="rgb(239, 68, 68)" />
                    </linearGradient>
                  </defs>

                  <CartesianGrid 
                    strokeDasharray="2 4" 
                    vertical={false} 
                    stroke="rgba(148, 163, 184, 0.15)"
                    strokeWidth={1}
                  />
                  <XAxis
                    dataKey="name"
                    axisLine={false}
                    tickLine={false}
                    tick={{ 
                      fill: 'rgb(148, 163, 184)', 
                      fontSize: 11,
                      fontWeight: 500,
                    }}
                    dy={10}
                    interval="preserveEnd"
                  />
                  <YAxis
                    domain={[yMin, yMax]}
                    axisLine={false}
                    tickLine={false}
                    tick={{ 
                      fill: 'rgb(148, 163, 184)', 
                      fontSize: 11,
                      fontWeight: 500,
                    }}
                    tickFormatter={(value: number) => {
                      const absValue = Math.abs(value);
                      let formatted = '';
                      if (absValue >= 1000000) {
                        formatted = `${(absValue / 1000000).toFixed(1)}M`;
                      } else if (absValue >= 1000) {
                        formatted = `${(absValue / 1000).toFixed(1)}K`;
                      } else {
                        formatted = absValue.toFixed(0);
                      }
                      return value < 0 ? `-$${formatted}` : ` $${formatted}`;
                    }}
                    width={90}
                    orientation="left"
                    tickMargin={5}
                    interval={0}
                    ticks={[yMin, yMin + (yMax - yMin) * 0.33, yMin + (yMax - yMin) * 0.67, yMax]}
                  />
                  <Tooltip 
                    content={<CustomTooltip />} 
                    cursor={{
                      stroke: 'rgba(148, 163, 184, 0.2)',
                      strokeWidth: 1,
                      strokeDasharray: '3 3'
                    }}
                  />
                  <Area
                    type="monotone"
                    dataKey="value"
                    stroke="url(#strokeColor)"
                    strokeWidth={2.1}
                    fill="url(#splitColor)"
                    isAnimationActive={false}
                    dot={false}
                    activeDot={{
                      r: 5,
                      fill: '#2563eb',
                      stroke: '#ffffff',
                      strokeWidth: 2,
                    }}
                  />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </div>

          <div className="bg-gray-800/50 dark:bg-gray-900 rounded-lg p-4">
            <h3 className="text-lg font-semibold mb-4 px-2">Trades</h3>
            <div className="relative w-full">
              <table className="w-full table-fixed border-separate border-spacing-0">
                <colgroup>
                  <col className="w-[13%]" />
                  <col className="w-[11%]" />
                  <col className="w-[10%]" />
                  <col className="w-[12%]" />
                  <col className="w-[12%]" />
                  <col className="w-[11%]" />
                  <col className="w-[16%]" />
                </colgroup>
                <thead>
                  <tr className="text-gray-400">
                    <th className="text-center font-medium py-3 px-4">Time</th>
                    <th className="text-center font-medium py-3 px-4">Symbol</th>
                    <th className="text-center font-medium py-3 px-4">Type</th>
                    <th className="text-right font-medium py-3 px-4">Entry</th>
                    <th className="text-right font-medium py-3 px-4">Exit</th>
                    <th className="text-center font-medium py-3 px-4">Quantity</th>
                    <th className="text-right font-medium py-3 px-4">P&L</th>
                  </tr>
                </thead>
                <tbody>
                  {sortedTrades.map((trade, index) => (
                    <tr 
                      key={trade.id} 
                      className={`
                        border-t border-gray-700/50
                        ${index % 2 === 0 ? 'bg-gray-800/20' : ''}
                        hover:bg-gray-700/30 transition-colors duration-150
                      `}
                    >
                      <td className="py-3 px-4 text-left whitespace-nowrap overflow-hidden text-ellipsis">
                        {new Date(trade.exit_date).toLocaleTimeString()}
                      </td>
                      <td className="py-3 px-4 text-left font-medium whitespace-nowrap overflow-hidden text-ellipsis">
                        {trade.symbol}
                      </td>
                      <td className="py-3 px-4 text-center whitespace-nowrap overflow-hidden text-ellipsis">
                        {trade.type}
                      </td>
                      <td className="py-3 px-4 text-right font-medium whitespace-nowrap overflow-hidden text-ellipsis">
                        {formatCurrency(trade.entry_price)}
                      </td>
                      <td className="py-3 px-4 text-right font-medium whitespace-nowrap overflow-hidden text-ellipsis">
                        {formatCurrency(trade.exit_price)}
                      </td>
                      <td className="py-3 px-4 text-center whitespace-nowrap overflow-hidden text-ellipsis">
                        {formatQuantity(trade.quantity)}
                      </td>
                      <td className={`
                        py-3 px-4 text-right font-medium whitespace-nowrap overflow-hidden text-ellipsis
                        ${trade.pnl >= 0 ? 'text-green-500' : 'text-red-500'}
                      `}>
                        {formatCurrency(Math.abs(trade.pnl))}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <style jsx global>{`
          .fixed-section {
            position: absolute;
            top: 0;
            left: 33px;
            right: 33px;
            background: var(--background);
            z-index: 1;
          }

          .scrollbar-content {
            scrollbar-gutter: stable;
            scrollbar-width: thin;
            scrollbar-color: transparent transparent;
            transition: scrollbar-color 0.3s ease;
            padding-right: 55px;
          }

          .scrollbar-content:hover {
            scrollbar-color: rgba(155, 155, 155, 0.5) transparent;
          }

          .scrollbar-content::-webkit-scrollbar {
            width: 6px;
            background: transparent;
          }

          .scrollbar-content::-webkit-scrollbar-thumb {
            background-color: transparent;
            border-radius: 20px;
            transition: background-color 0.3s ease;
          }

          .scrollbar-content:hover::-webkit-scrollbar-thumb {
            background-color: rgba(155, 155, 155, 0.5);
          }

          .scrollbar-content:hover::-webkit-scrollbar-thumb:hover {
            background-color: rgba(155, 155, 155, 0.7);
          }
        `}</style>
      </DialogContent>
    </Dialog>
  );
};

update the previous code with the next instructions and return me the full updated code;
import React from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { Trade, DayStats } from '@/types/trade'

interface DayTradesModalProps {
  isOpen: boolean
  onClose: () => void
  selectedDay: {
    day: number
    trades: Trade[]
    stats: DayStats | null
  } | null
  currentDate: Date
  onNewTrade: (trade: Trade) => void
  onNavigate: (increment: number) => void
}

export function DayTradesModal({
  isOpen,
  onClose,
  selectedDay,
  currentDate,
  onNewTrade,
  onNavigate
}: DayTradesModalProps) {
  if (!isOpen || !selectedDay) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="relative bg-gray-900 rounded-lg w-full max-w-4xl mx-4">
        {/* Navigation Buttons */}
        <button
          onClick={() => onNavigate(-1)}
          className="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-12 p-2 rounded-full bg-gray-800 hover:bg-gray-700 transition-colors"
        >
          <ChevronLeft className="h-6 w-6 text-gray-300" />
        </button>
        
        <button
          onClick={() => onNavigate(1)}
          className="absolute right-0 top-1/2 -translate-y-1/2 translate-x-12 p-2 rounded-full bg-gray-800 hover:bg-gray-700 transition-colors"
        >
          <ChevronRight className="h-6 w-6 text-gray-300" />
        </button>

        {/* Modal Content */}
        <div className="p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-xl font-bold">
              {new Date(
                currentDate.getFullYear(),
                currentDate.getMonth(),
                selectedDay.day
              ).toLocaleDateString('en-US', {
                weekday: 'long',
                year: 'numeric',
                month: 'long',
                day: 'numeric'
              })}
            </h2>
            <button
              onClick={onClose}
              className="p-2 hover:bg-gray-800 rounded-full transition-colors"
            >
              <span className="sr-only">Close</span>
              <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
          
          {/* Stats Section */}
          {selectedDay.stats && (
            <div className="mb-4">
              <p className="text-lg">
                PnL: <span className={selectedDay.stats.pnl >= 0 ? 'text-green-500' : 'text-red-500'}>
                  ${selectedDay.stats.pnl.toFixed(2)}
                </span>
              </p>
              <p className="text-gray-400">Win Rate: {selectedDay.stats.winRate}</p>
            </div>
          )}
          
          {/* Trades List */}
          <div className="mt-4">
            {selectedDay.trades.length > 0 ? (
              selectedDay.trades.map((trade, index) => (
                <div key={index} className="border-t border-gray-800 py-2">
                  <div className="flex justify-between items-center">
                    <div>
                      <span className="font-medium">{trade.symbol}</span>
                      <span className="ml-2 text-gray-400">{trade.type}</span>
                    </div>
                    <span className={`font-medium ${trade.pnl >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                      ${trade.pnl.toFixed(2)}
                    </span>
                  </div>
                </div>
              ))
            ) : (
              <p className="text-gray-500">No trades for this day</p>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}