["use client";

import React, { useState, useMemo, useRef, useEffect } from "react";
import {
  PieChart,
  Pie,
  Cell,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";

// SVG ICONS
const Icon = ({ className, children }: { className?: string; children: React.ReactNode }) => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
    stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
    {children}
  </svg>
);
const Home = ({ className }: { className?: string }) => <Icon className={className}><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" /><polyline points="9 22 9 12 15 12 15 22" /></Icon>;
const DollarSign = ({ className }: { className?: string }) => <Icon className={className}><line x1="12" x2="12" y1="2" y2="22" /><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" /></Icon>;
const TrendingUp = ({ className }: { className?: string }) => <Icon className={className}><polyline points="22 7 13.5 15.5 8.5 10.5 2 17" /><polyline points="16 7 22 7 22 13" /></Icon>;
const TrendingDown = ({ className }: { className?: string }) => <Icon className={className}><polyline points="22 17 13.5 8.5 8.5 13.5 2 7" /><polyline points="16 17 22 17 22 11" /></Icon>;
const PiggyBank = ({ className }: { className?: string }) => <Icon className={className}><path d="M10 20v-6h4v6" /><path d="M18.5 7.5c0-2.5-2.5-5-5-5A5.5 5.5 0 0 0 7 7.5c0 .8.2 1.5.5 2.1L6 11v4h12v-4l-1.5-1.4c.3-.6.5-1.3.5-2.1Z" /><path d="M2 11h2" /><path d="M20 11h2" /></Icon>;
const Menu = ({ className }: { className?: string }) => <Icon className={className}><line x1="4" x2="20" y1="12" y2="12" /><line x1="4" x2="20" y1="6" y2="6" /><line x1="4" x2="20" y1="18" y2="18" /></Icon>;
const Sun = ({ className }: { className?: string }) => <Icon className={className}><circle cx="12" cy="12" r="4" /><path d="M12 2v2" /><path d="M12 20v2" /><path d="m4.93 4.93 1.41 1.41" /><path d="m17.66 17.66 1.41 1.41" /><path d="M2 12h2" /><path d="M20 12h2" /><path d="m6.34 17.66-1.41 1.41" /><path d="m19.07 4.93-1.41 1.41" /></Icon>;
const Moon = ({ className }: { className?: string }) => <Icon className={className}><path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" /></Icon>;
const BarChart3 = ({ className }: { className?: string }) => <Icon className={className}><path d="M3 3v18h18" /><path d="M18 17V9" /><path d="M13 17V5" /><path d="M8 17v-3" /></Icon>;
const Target = ({ className }: { className?: string }) => <Icon className={className}><circle cx="12" cy="12" r="10" /><circle cx="12" cy="12" r="6" /><circle cx="12" cy="12" r="2" /></Icon>;
const Wallet = ({ className }: { className?: string }) => <Icon className={className}><path d="M21 10H3a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h18a1 1 0 0 0 1-1v-9a1 1 0 0 0-1-1Z"/><path d="M22 6V5a1 1 0 0 0-1-1H3a1 1 0 0 0-1 1v1"/><circle cx="18" cy="16" r="1"/></Icon>;
const Activity = ({ className }: { className?: string }) => <Icon className={className}><path d="M22 12h-4l-3 9L9 3l-3 9H2" /></Icon>;
const Calendar = ({ className }: { className?: string }) => <Icon className={className}><rect x="3" y="4" width="18" height="18" rx="2" ry="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" /></Icon>;
const ChevronLeft = ({ className }: { className?: string }) => <Icon className={className}><path d="m15 18-6-6 6-6" /></Icon>;
const ChevronRight = ({ className }: { className?: string }) => <Icon className={className}><path d="m9 18 6-6-6-6" /></Icon>;
const Filter = ({ className }: { className?: string }) => <Icon className={className}><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></Icon>;

// Button Component
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: 'default' | 'destructive' | 'outline' | 'secondary' | 'ghost' | 'link';
  size?: 'default' | 'sm' | 'lg' | 'icon';
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className = '', variant = 'default', size = 'default', ...props }, ref) => {
    const baseClasses = 'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50';
    const variantClasses = {
      default: 'bg-primary text-primary-foreground hover:bg-primary/90',
      destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
      outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
      secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
      ghost: 'hover:bg-accent hover:text-accent-foreground',
      link: 'text-primary underline-offset-4 hover:underline',
    };
    const sizeClasses = {
      default: 'h-10 px-4 py-2',
      sm: 'h-9 rounded-md px-3',
      lg: 'h-11 rounded-md px-8',
      icon: 'h-10 w-10',
    };
    const combinedClasses = `${baseClasses} ${variantClasses[variant]} ${sizeClasses[size]} ${className}`;
    return <button className={combinedClasses} ref={ref} {...props} />;
  }
);
Button.displayName = 'Button';

// Card Components
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div ref={ref} className={`rounded-lg border bg-card text-card-foreground shadow-sm ${className || ''}`} {...props} />
  )
);
Card.displayName = 'Card';

const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div ref={ref} className={`flex flex-col space-y-1.5 p-6 ${className || ''}`} {...props} />
  )
);
CardHeader.displayName = 'CardHeader';

const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
  ({ className, ...props }, ref) => (
    <h3 ref={ref} className={`text-2xl font-semibold leading-none tracking-tight ${className || ''}`} {...props} />
  )
);
CardTitle.displayName = 'CardTitle';

const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div ref={ref} className={`p-6 pt-0 ${className || ''}`} {...props} />
  )
);
CardContent.displayName = 'CardContent';

// Badge Component for Filters
const Badge = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement> & { variant?: string, active?: boolean }>(
  ({ className, variant = 'default', active = false, ...props }, ref) => {
    const baseClasses = 'inline-flex items-center rounded-full px-3 py-1 text-sm font-medium transition-colors';
    const variantClasses = active 
      ? 'bg-purple-600 text-white hover:bg-purple-700'
      : 'bg-gray-100 text-gray-800 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600';
    
    return (
      <div ref={ref} className={`${baseClasses} ${variantClasses} ${className || ''}`} {...props} />
    );
  }
);
Badge.displayName = 'Badge';

// Improved date picker that uses a better calendar UI
interface DatePickerProps {
  value: string;
  onChange: (date: string) => void;
  darkMode: boolean;
  label?: string;
  minDate?: Date;
  maxDate?: Date;
}

const DatePicker: React.FC<DatePickerProps> = ({ 
  value, 
  onChange, 
  darkMode, 
  label, 
  minDate,
  maxDate 
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [currentMonth, setCurrentMonth] = useState(() => value ? new Date(value) : new Date());
  const containerRef = useRef<HTMLDivElement>(null);
  
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);
  
  const formatDisplayDate = (dateStr: string) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  };
  
  const handlePreviousMonth = () => {
    setCurrentMonth(prev => new Date(prev.getFullYear(), prev.getMonth() - 1, 1));
  };
  
  const handleNextMonth = () => {
    setCurrentMonth(prev => new Date(prev.getFullYear(), prev.getMonth() + 1, 1));
  };
  
  // Get days for the current month view
  const getDaysArray = () => {
    const year = currentMonth.getFullYear();
    const month = currentMonth.getMonth();
    
    const firstDayOfMonth = new Date(year, month, 1).getDay();
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    
    // Create array for the days
    const days = [];
    
    // Add empty slots for previous month days
    for (let i = 0; i < firstDayOfMonth; i++) {
      days.push(null);
    }
    
    // Add days of the current month
    for (let i = 1; i <= daysInMonth; i++) {
      days.push(new Date(year, month, i));
    }
    
    return days;
  };
  
  const days = getDaysArray();
  const dayNames = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

  const isToday = (date: Date) => {
    const today = new Date();
    return date.getDate() === today.getDate() && 
           date.getMonth() === today.getMonth() && 
           date.getFullYear() === today.getFullYear();
  };
  
  const isSelected = (date: Date) => {
    if (!value) return false;
    const selectedDate = new Date(value);
    return date.getDate() === selectedDate.getDate() && 
           date.getMonth() === selectedDate.getMonth() && 
           date.getFullYear() === selectedDate.getFullYear();
  };
  
  const isDisabled = (date: Date) => {
    if (minDate && date < minDate) return true;
    if (maxDate && date > maxDate) return true;
    return false;
  };
  
  return (
    <div ref={containerRef} className="relative inline-block">
      {label && (
        <label className={`block text-sm font-medium mb-1 ${darkMode ? 'text-gray-300' : 'text-gray-700'}`}>
          {label}
        </label>
      )}
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className={`
          flex items-center justify-between w-full rounded-md border p-2 shadow-sm transition-all
          ${darkMode 
            ? 'bg-gray-700 border-gray-600 text-white hover:border-purple-500 focus:border-purple-500' 
            : 'bg-white border-gray-300 text-gray-900 hover:border-purple-500 focus:border-purple-500'
          }
          h-10 px-3 text-sm focus:outline-none
        `}
      >
        <div className="flex items-center gap-2">
          <Calendar className="h-4 w-4" />
          <span>{formatDisplayDate(value)}</span>
        </div>
        <ChevronRight className={`h-4 w-4 transition-transform ${isOpen ? 'rotate-90' : ''}`} />
      </button>
      
      {isOpen && (
        <div 
          className={`
            absolute z-50 mt-1 rounded-lg border shadow-lg overflow-hidden
            ${darkMode ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'}
            w-72
          `}
        >
          <div className="p-3">
            {/* Calendar header */}
            <div className="flex items-center justify-between mb-4">
              <button
                type="button"
                onClick={handlePreviousMonth}
                className={`
                  p-1 rounded-full transition-colors
                  ${darkMode 
                    ? 'text-gray-300 hover:bg-gray-700 hover:text-white' 
                    : 'text-gray-700 hover:bg-purple-100 hover:text-purple-600'}
                `}
              >
                <ChevronLeft className="h-5 w-5" />
              </button>
              <h3 className={`text-sm font-semibold ${darkMode ? 'text-white' : 'text-gray-900'}`}>
                {months[currentMonth.getMonth()]} {currentMonth.getFullYear()}
              </h3>
              <button
                type="button"
                onClick={handleNextMonth}
                className={`
                  p-1 rounded-full transition-colors
                  ${darkMode 
                    ? 'text-gray-300 hover:bg-gray-700 hover:text-white' 
                    : 'text-gray-700 hover:bg-purple-100 hover:text-purple-600'}
                `}
              >
                <ChevronRight className="h-5 w-5" />
              </button>
            </div>
            
            {/* Day names */}
            <div className="grid grid-cols-7 mb-2">
              {dayNames.map(day => (
                <div key={day} className={`text-center text-xs font-medium py-1 ${darkMode ? 'text-gray-400' : 'text-gray-500'}`}>
                  {day}
                </div>
              ))}
            </div>
            
            {/* Calendar days */}
            <div className="grid grid-cols-7 gap-1">
              {days.map((day, i) => (
                <div key={i} className="aspect-square">
                  {day ? (
                    <button
                      type="button"
                      disabled={isDisabled(day)}
                      onClick={() => {
                        // Fixed: Use UTC to avoid timezone issues causing date to shift
                        const year = day.getFullYear();
                        const month = day.getMonth() + 1;
                        const date = day.getDate();
                        const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${date.toString().padStart(2, '0')}`;
                        onChange(formattedDate);
                        setIsOpen(false);
                      }}
                      className={`
                        w-full h-full flex items-center justify-center rounded-full text-sm font-medium
                        transition-colors
                        ${isSelected(day) 
                          ? 'bg-purple-600 text-white hover:bg-purple-700' 
                          : isToday(day)
                            ? 'border border-purple-400 dark:border-purple-600'
                            : darkMode 
                              ? 'hover:bg-gray-700 text-gray-200' 
                              : 'hover:bg-gray-100 text-gray-700 hover:text-gray-900'
                        }
                        ${isDisabled(day) ? 'opacity-30 cursor-not-allowed' : 'cursor-pointer'}
                      `}
                    >
                      {day.getDate()}
                    </button>
                  ) : (
                    <div className="w-full h-full"></div>
                  )}
                </div>
              ))}
            </div>
          </div>
          
          {/* Quick select buttons - Apply button removed */}
          <div className={`
            flex items-center justify-between p-3 border-t
            ${darkMode ? 'border-gray-700 bg-gray-750' : 'border-gray-200 bg-gray-50'}
          `}>
            <button
              type="button"
              onClick={() => {
                const today = new Date();
                const year = today.getFullYear();
                const month = today.getMonth() + 1;
                const date = today.getDate();
                const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${date.toString().padStart(2, '0')}`;
                onChange(formattedDate);
                setIsOpen(false);
              }}
              className={`
                text-xs font-medium px-2 py-1 rounded hover:underline
                ${darkMode ? 'text-purple-400' : 'text-purple-600'}
              `}
            >
              Today
            </button>
            <button
              type="button"
              onClick={() => setIsOpen(false)}
              className={`
                text-xs font-medium px-3 py-1 rounded
                ${darkMode ? 'text-gray-300 hover:bg-gray-700' : 'text-gray-700 hover:bg-gray-200'}
              `}
            >
              Cancel
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

// Improved Date Range Picker with better calendar
const DateRangePicker = ({
  startDate,
  endDate,
  onStartDateChange,
  onEndDateChange,
  darkMode,
}: {
  startDate: string;
  endDate: string;
  onStartDateChange: (date: string) => void;
  onEndDateChange: (date: string) => void;
  darkMode: boolean;
}) => {
  return (
    <div className="flex items-center gap-2">
      <DatePicker
        value={startDate}
        onChange={onStartDateChange}
        darkMode={darkMode}
        maxDate={endDate ? new Date(endDate) : undefined}
      />
      
      <span className={`mx-2 ${darkMode ? 'text-gray-400' : 'text-gray-500'}`}>to</span>
      
      <DatePicker
        value={endDate}
        onChange={onEndDateChange}
        darkMode={darkMode}
        minDate={startDate ? new Date(startDate) : undefined}
        maxDate={new Date()}
      />
    </div>
  );
};

// Improved SegmentedControl for view type selection with better contrast
const SegmentedControl = ({ 
  options, 
  value, 
  onChange, 
  darkMode 
}: { 
  options: {value: string, label: string}[],
  value: string,
  onChange: (value: string) => void,
  darkMode: boolean
}) => {
  return (
    <div className={`
      inline-flex p-1 rounded-lg
      ${darkMode ? 'bg-gray-700' : 'bg-gray-100'}
    `}>
      {options.map(option => (
        <button
          key={option.value}
          onClick={() => onChange(option.value)}
          className={`
            px-4 py-1.5 text-sm font-medium rounded-md transition-colors
            ${value === option.value 
              ? (darkMode 
                  ? 'bg-purple-600 text-white shadow-sm' 
                  : 'bg-white text-purple-800 shadow-sm') 
              : (darkMode 
                  ? 'text-gray-200 hover:text-white hover:bg-gray-600' 
                  : 'text-gray-700 hover:text-gray-900 hover:bg-gray-200')
            }
          `}
        >
          {option.label}
        </button>
      ))}
    </div>
  );
};

// Types
interface ExpenseData {
  id: string;
  amount: number;
  category: string;
  date: string;
  description: string;
  type: 'expense' | 'income';
}
interface CategoryData {
  name: string;
  value: number;
  color: string;
}

// Category colors
const categoryColors: { [key: string]: string } = {
  Essentials: '#3B82F6',
  Food: '#F59E0B',
  Transport: '#8B5CF6',
  Entertainment: '#10B981',
  Other: '#EF4444',
  Salary: '#14B8A6'
};

// Fixed mock data that won't change on refresh
const FIXED_MOCK_DATA: ExpenseData[] = [
  // January 2025
  { id: '1', amount: 3500, category: 'Salary', date: '2025-01-01', description: 'Salary income', type: 'income' },
  { id: '2', amount: 1200, category: 'Essentials', date: '2025-01-02', description: 'Essentials expense', type: 'expense' },
  { id: '3', amount: 150, category: 'Food', date: '2025-01-02', description: 'Food expense', type: 'expense' },
  { id: '4', amount: 80, category: 'Transport', date: '2025-01-03', description: 'Transport expense', type: 'expense' },
  { id: '5', amount: 200, category: 'Entertainment', date: '2025-01-05', description: 'Entertainment expense', type: 'expense' },
  { id: '6', amount: 220, category: 'Food', date: '2025-01-06', description: 'Food expense', type: 'expense' },
  { id: '7', amount: 120, category: 'Transport', date: '2025-01-07', description: 'Transport expense', type: 'expense' },
  { id: '8', amount: 350, category: 'Other', date: '2025-01-08', description: 'Other expense', type: 'expense' },
  { id: '9', amount: 180, category: 'Food', date: '2025-01-10', description: 'Food expense', type: 'expense' },
  { id: '10', amount: 90, category: 'Transport', date: '2025-01-11', description: 'Transport expense', type: 'expense' },
  { id: '11', amount: 2200, category: 'Salary', date: '2025-01-15', description: 'Salary income', type: 'income' },
  { id: '12', amount: 800, category: 'Essentials', date: '2025-01-16', description: 'Essentials expense', type: 'expense' },
  { id: '13', amount: 250, category: 'Food', date: '2025-01-17', description: 'Food expense', type: 'expense' },
  { id: '14', amount: 150, category: 'Entertainment', date: '2025-01-18', description: 'Entertainment expense', type: 'expense' },
  { id: '15', amount: 100, category: 'Transport', date: '2025-01-20', description: 'Transport expense', type: 'expense' },
  { id: '16', amount: 300, category: 'Other', date: '2025-01-22', description: 'Other expense', type: 'expense' },
  { id: '17', amount: 190, category: 'Food', date: '2025-01-23', description: 'Food expense', type: 'expense' },
  { id: '18', amount: 110, category: 'Transport', date: '2025-01-25', description: 'Transport expense', type: 'expense' },
  { id: '19', amount: 450, category: 'Essentials', date: '2025-01-26', description: 'Essentials expense', type: 'expense' },
  { id: '20', amount: 280, category: 'Entertainment', date: '2025-01-28', description: 'Entertainment expense', type: 'expense' },
  
  // February 2025
  { id: '21', amount: 3500, category: 'Salary', date: '2025-02-01', description: 'Salary income', type: 'income' },
  { id: '22', amount: 1100, category: 'Essentials', date: '2025-02-02', description: 'Essentials expense', type: 'expense' },
  { id: '23', amount: 170, category: 'Food', date: '2025-02-03', description: 'Food expense', type: 'expense' },
  { id: '24', amount: 95, category: 'Transport', date: '2025-02-04', description: 'Transport expense', type: 'expense' },
  { id: '25', amount: 320, category: 'Entertainment', date: '2025-02-05', description: 'Entertainment expense', type: 'expense' },
  { id: '26', amount: 200, category: 'Food', date: '2025-02-07', description: 'Food expense', type: 'expense' },
  { id: '27', amount: 130, category: 'Transport', date: '2025-02-08', description: 'Transport expense', type: 'expense' },
  { id: '28', amount: 400, category: 'Other', date: '2025-02-10', description: 'Other expense', type: 'expense' },
  { id: '29', amount: 160, category: 'Food', date: '2025-02-12', description: 'Food expense', type: 'expense' },
  { id: '30', amount: 85, category: 'Transport', date: '2025-02-14', description: 'Transport expense', type: 'expense' },
  { id: '31', amount: 2500, category: 'Salary', date: '2025-02-15', description: 'Salary income', type: 'income' },
  { id: '32', amount: 900, category: 'Essentials', date: '2025-02-16', description: 'Essentials expense', type: 'expense' },
  { id: '33', amount: 230, category: 'Food', date: '2025-02-18', description: 'Food expense', type: 'expense' },
  { id: '34', amount: 180, category: 'Entertainment', date: '2025-02-20', description: 'Entertainment expense', type: 'expense' },
  { id: '35', amount: 120, category: 'Transport', date: '2025-02-22', description: 'Transport expense', type: 'expense' },
  { id: '36', amount: 350, category: 'Other', date: '2025-02-24', description: 'Other expense', type: 'expense' },
  { id: '37', amount: 210, category: 'Food', date: '2025-02-25', description: 'Food expense', type: 'expense' },
  { id: '38', amount: 140, category: 'Transport', date: '2025-02-26', description: 'Transport expense', type: 'expense' },
  { id: '39', amount: 500, category: 'Essentials', date: '2025-02-27', description: 'Essentials expense', type: 'expense' },
  { id: '40', amount: 260, category: 'Entertainment', date: '2025-02-28', description: 'Entertainment expense', type: 'expense' },

  // March 2025
  { id: '41', amount: 3500, category: 'Salary', date: '2025-03-01', description: 'Salary income', type: 'income' },
  { id: '42', amount: 1300, category: 'Essentials', date: '2025-03-02', description: 'Essentials expense', type: 'expense' },
  { id: '43', amount: 140, category: 'Food', date: '2025-03-03', description: 'Food expense', type: 'expense' },
  { id: '44', amount: 75, category: 'Transport', date: '2025-03-04', description: 'Transport expense', type: 'expense' },
  { id: '45', amount: 250, category: 'Entertainment', date: '2025-03-06', description: 'Entertainment expense', type: 'expense' },
  { id: '46', amount: 190, category: 'Food', date: '2025-03-08', description: 'Food expense', type: 'expense' },
  { id: '47', amount: 115, category: 'Transport', date: '2025-03-10', description: 'Transport expense', type: 'expense' },
  { id: '48', amount: 380, category: 'Other', date: '2025-03-12', description: 'Other expense', type: 'expense' },
  { id: '49', amount: 175, category: 'Food', date: '2025-03-14', description: 'Food expense', type: 'expense' },
  { id: '50', amount: 105, category: 'Transport', date: '2025-03-15', description: 'Transport expense', type: 'expense' },
  { id: '51', amount: 2800, category: 'Salary', date: '2025-03-15', description: 'Salary income', type: 'income' },
  { id: '52', amount: 950, category: 'Essentials', date: '2025-03-17', description: 'Essentials expense', type: 'expense' },
  { id: '53', amount: 265, category: 'Food', date: '2025-03-19', description: 'Food expense', type: 'expense' },
  { id: '54', amount: 195, category: 'Entertainment', date: '2025-03-21', description: 'Entertainment expense', type: 'expense' },
  { id: '55', amount: 135, category: 'Transport', date: '2025-03-23', description: 'Transport expense', type: 'expense' },
  { id: '56', amount: 420, category: 'Other', date: '2025-03-25', description: 'Other expense', type: 'expense' },
  { id: '57', amount: 225, category: 'Food', date: '2025-03-27', description: 'Food expense', type: 'expense' },
  { id: '58', amount: 155, category: 'Transport', date: '2025-03-29', description: 'Transport expense', type: 'expense' },
  { id: '59', amount: 550, category: 'Essentials', date: '2025-03-30', description: 'Essentials expense', type: 'expense' },
  { id: '60', amount: 290, category: 'Entertainment', date: '2025-03-31', description: 'Entertainment expense', type: 'expense' },

  // April 2025
  { id: '61', amount: 3500, category: 'Salary', date: '2025-04-01', description: 'Salary income', type: 'income' },
  { id: '62', amount: 1250, category: 'Essentials', date: '2025-04-02', description: 'Essentials expense', type: 'expense' },
  { id: '63', amount: 165, category: 'Food', date: '2025-04-04', description: 'Food expense', type: 'expense' },
  { id: '64', amount: 90, category: 'Transport', date: '2025-04-05', description: 'Transport expense', type: 'expense' },
  { id: '65', amount: 310, category: 'Entertainment', date: '2025-04-07', description: 'Entertainment expense', type: 'expense' },
  { id: '66', amount: 205, category: 'Food', date: '2025-04-09', description: 'Food expense', type: 'expense' },
  { id: '67', amount: 125, category: 'Transport', date: '2025-04-11', description: 'Transport expense', type: 'expense' },
  { id: '68', amount: 390, category: 'Other', date: '2025-04-13', description: 'Other expense', type: 'expense' },
  { id: '69', amount: 185, category: 'Food', date: '2025-04-15', description: 'Food expense', type: 'expense' },
  { id: '70', amount: 95, category: 'Transport', date: '2025-04-15', description: 'Transport expense', type: 'expense' },
  { id: '71', amount: 2600, category: 'Salary', date: '2025-04-15', description: 'Salary income', type: 'income' },
  { id: '72', amount: 875, category: 'Essentials', date: '2025-04-18', description: 'Essentials expense', type: 'expense' },
  { id: '73', amount: 245, category: 'Food', date: '2025-04-20', description: 'Food expense', type: 'expense' },
  { id: '74', amount: 175, category: 'Entertainment', date: '2025-04-22', description: 'Entertainment expense', type: 'expense' },
  { id: '75', amount: 145, category: 'Transport', date: '2025-04-24', description: 'Transport expense', type: 'expense' },
  { id: '76', amount: 460, category: 'Other', date: '2025-04-26', description: 'Other expense', type: 'expense' },
  { id: '77', amount: 235, category: 'Food', date: '2025-04-28', description: 'Food expense', type: 'expense' },
  { id: '78', amount: 165, category: 'Transport', date: '2025-04-29', description: 'Transport expense', type: 'expense' },
  { id: '79', amount: 600, category: 'Essentials', date: '2025-04-30', description: 'Essentials expense', type: 'expense' },
  { id: '80', amount: 270, category: 'Entertainment', date: '2025-04-30', description: 'Entertainment expense', type: 'expense' },

  // May 2025
  { id: '81', amount: 3500, category: 'Salary', date: '2025-05-01', description: 'Salary income', type: 'income' },
  { id: '82', amount: 1150, category: 'Essentials', date: '2025-05-03', description: 'Essentials expense', type: 'expense' },
  { id: '83', amount: 155, category: 'Food', date: '2025-05-05', description: 'Food expense', type: 'expense' },
  { id: '84', amount: 85, category: 'Transport', date: '2025-05-07', description: 'Transport expense', type: 'expense' },
  { id: '85', amount: 280, category: 'Entertainment', date: '2025-05-09', description: 'Entertainment expense', type: 'expense' },
  { id: '86', amount: 195, category: 'Food', date: '2025-05-11', description: 'Food expense', type: 'expense' },
  { id: '87', amount: 135, category: 'Transport', date: '2025-05-13', description: 'Transport expense', type: 'expense' },
  { id: '88', amount: 410, category: 'Other', date: '2025-05-15', description: 'Other expense', type: 'expense' },
  { id: '89', amount: 170, category: 'Food', date: '2025-05-15', description: 'Food expense', type: 'expense' },
  { id: '90', amount: 100, category: 'Transport', date: '2025-05-15', description: 'Transport expense', type: 'expense' },
  { id: '91', amount: 2700, category: 'Salary', date: '2025-05-15', description: 'Salary income', type: 'income' },
  { id: '92', amount: 925, category: 'Essentials', date: '2025-05-19', description: 'Essentials expense', type: 'expense' },
  { id: '93', amount: 255, category: 'Food', date: '2025-05-21', description: 'Food expense', type: 'expense' },
  { id: '94', amount: 185, category: 'Entertainment', date: '2025-05-23', description: 'Entertainment expense', type: 'expense' },
  { id: '95', amount: 150, category: 'Transport', date: '2025-05-25', description: 'Transport expense', type: 'expense' },
  { id: '96', amount: 440, category: 'Other', date: '2025-05-27', description: 'Other expense', type: 'expense' },
  { id: '97', amount: 240, category: 'Food', date: '2025-05-29', description: 'Food expense', type: 'expense' },
  { id: '98', amount: 170, category: 'Transport', date: '2025-05-30', description: 'Transport expense', type: 'expense' },
  { id: '99', amount: 575, category: 'Essentials', date: '2025-05-31', description: 'Essentials expense', type: 'expense' },
  { id: '100', amount: 300, category: 'Entertainment', date: '2025-05-31', description: 'Entertainment expense', type: 'expense' },

  // June 2025
  { id: '101', amount: 3500, category: 'Salary', date: '2025-06-01', description: 'Salary income', type: 'income' },
  { id: '102', amount: 1225, category: 'Essentials', date: '2025-06-02', description: 'Essentials expense', type: 'expense' },
  { id: '103', amount: 145, category: 'Food', date: '2025-06-04', description: 'Food expense', type: 'expense' },
  { id: '104', amount: 80, category: 'Transport', date: '2025-06-06', description: 'Transport expense', type: 'expense' },
  { id: '105', amount: 290, category: 'Entertainment', date: '2025-06-08', description: 'Entertainment expense', type: 'expense' },
  { id: '106', amount: 215, category: 'Food', date: '2025-06-10', description: 'Food expense', type: 'expense' },
  { id: '107', amount: 140, category: 'Transport', date: '2025-06-12', description: 'Transport expense', type: 'expense' },
  { id: '108', amount: 425, category: 'Other', date: '2025-06-14', description: 'Other expense', type: 'expense' },
  { id: '109', amount: 180, category: 'Food', date: '2025-06-15', description: 'Food expense', type: 'expense' },
  { id: '110', amount: 110, category: 'Transport', date: '2025-06-15', description: 'Transport expense', type: 'expense' },
  { id: '111', amount: 2900, category: 'Salary', date: '2025-06-15', description: 'Salary income', type: 'income' },
  { id: '112', amount: 850, category: 'Essentials', date: '2025-06-18', description: 'Essentials expense', type: 'expense' },
  { id: '113', amount: 260, category: 'Food', date: '2025-06-20', description: 'Food expense', type: 'expense' },
  { id: '114', amount: 190, category: 'Entertainment', date: '2025-06-22', description: 'Entertainment expense', type: 'expense' },
  { id: '115', amount: 155, category: 'Transport', date: '2025-06-24', description: 'Transport expense', type: 'expense' },
  { id: '116', amount: 485, category: 'Other', date: '2025-06-26', description: 'Other expense', type: 'expense' },
  { id: '117', amount: 250, category: 'Food', date: '2025-06-28', description: 'Food expense', type: 'expense' },
  { id: '118', amount: 175, category: 'Transport', date: '2025-06-29', description: 'Transport expense', type: 'expense' },
];

const ExpenseTrackingDashboard = () => {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [darkMode, setDarkMode] = useState(false);
  const [viewType, setViewType] = useState('monthly');

  // Date range state
  const today = new Date();
  const defaultEnd = today.toISOString().split('T')[0];
  const defaultStart = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 29).toISOString().split('T')[0];
  const [startDate, setStartDate] = useState(defaultStart);
  const [endDate, setEndDate] = useState(defaultEnd);

  // Use the fixed mock data
  const allExpenses = FIXED_MOCK_DATA;

  // Filter by date range
  const expenses = useMemo(() => {
    return allExpenses.filter(item =>
      item.date >= startDate && item.date <= endDate
    );
  }, [allExpenses, startDate, endDate]);

  // Calculate filtered data based on view type
  const filteredExpensesByViewType = useMemo(() => {
    let filtered = expenses;
    
    if (viewType === 'daily') {
      // Find the latest date in the filtered expenses
      const latestDate = expenses.reduce((latest, item) => {
        return item.date > latest ? item.date : latest;
      }, expenses[0]?.date || endDate);
      
      filtered = expenses.filter(item => item.date === latestDate);
    } else if (viewType === 'weekly') {
      // Find the latest week that has data
      const sortedDates = [...new Set(expenses.map(e => e.date))].sort();
      if (sortedDates.length > 0) {
        const latestDate = new Date(sortedDates[sortedDates.length - 1]);
        const weekStart = new Date(latestDate);
        weekStart.setDate(latestDate.getDate() - latestDate.getDay());
        const weekEnd = new Date(weekStart);
        weekEnd.setDate(weekStart.getDate() + 6);
        
        const weekStartStr = weekStart.toISOString().split('T')[0];
        const weekEndStr = weekEnd.toISOString().split('T')[0];
        
        filtered = expenses.filter(item => 
          item.date >= weekStartStr && item.date <= weekEndStr
        );
      }
    } else if (viewType === 'monthly') {
      // Find the latest month that has data
      const sortedDates = [...new Set(expenses.map(e => e.date))].sort();
      if (sortedDates.length > 0) {
        const latestDate = new Date(sortedDates[sortedDates.length - 1]);
        const monthStart = new Date(latestDate.getFullYear(), latestDate.getMonth(), 1);
        const monthEnd = new Date(latestDate.getFullYear(), latestDate.getMonth() + 1, 0);
        
        const monthStartStr = monthStart.toISOString().split('T')[0];
        const monthEndStr = monthEnd.toISOString().split('T')[0];
        
        filtered = expenses.filter(item => 
          item.date >= monthStartStr && item.date <= monthEndStr
        );
      }
    }
    
    return filtered;
  }, [expenses, viewType]);

  // Calculate summary data based on view type
  const summaryData = useMemo(() => {
    const totalExpenses = filteredExpensesByViewType
      .filter(item => item.type === 'expense')
      .reduce((sum, item) => sum + item.amount, 0);
    const totalIncome = filteredExpensesByViewType
      .filter(item => item.type === 'income')
      .reduce((sum, item) => sum + item.amount, 0);
    const savings = totalIncome - totalExpenses;
    return { totalExpenses, totalIncome, savings };
  }, [filteredExpensesByViewType]);

  // Calculate category data for pie chart - also based on view type
  const categoryData: CategoryData[] = useMemo(() => {
    const categoryTotals = filteredExpensesByViewType
      .filter(item => item.type === 'expense')
      .reduce((acc, item) => {
        acc[item.category] = (acc[item.category] || 0) + item.amount;
        return acc;
      }, {} as Record<string, number>);
    return Object.entries(categoryTotals).map(([name, value]) => ({
      name,
      value,
      color: categoryColors[name] || '#6B7280'
    }));
  }, [filteredExpensesByViewType]);

  // Calculate trend data for line chart - still use full date range
  const trendData = useMemo(() => {
    const groupedData: { [key: string]: { expenses: number; income: number } } = {};
    expenses.forEach(item => {
      let key: string;
      const date = new Date(item.date);
      if (viewType === 'daily') {
        key = item.date;
      } else if (viewType === 'weekly') {
        const weekStart = new Date(date);
        weekStart.setDate(date.getDate() - date.getDay());
        key = weekStart.toISOString().split('T')[0];
      } else {
        key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
      }
      if (!groupedData[key]) {
        groupedData[key] = { expenses: 0, income: 0 };
      }
      if (item.type === 'expense') {
        groupedData[key].expenses += item.amount;
      } else {
        groupedData[key].income += item.amount;
      }
    });
    return Object.entries(groupedData)
      .map(([date, data]) => ({
        date,
        expenses: data.expenses,
        income: data.income,
        net: data.income - data.expenses
      }))
      .sort((a, b) => a.date.localeCompare(b.date))
      .slice(-20);
  }, [expenses, viewType]);

  const toggleSidebar = () => setSidebarOpen(!sidebarOpen);
  const toggleDarkMode = () => {
    setDarkMode(!darkMode);
    document.documentElement.classList.toggle('dark', !darkMode);
  };

  // Get period label for summary cards
  const getPeriodLabel = () => {
    if (filteredExpensesByViewType.length === 0) {
      return viewType === 'daily' ? 'Daily' : viewType === 'weekly' ? 'Weekly' : 'Monthly';
    }
    
    if (viewType === 'daily') {
      const date = filteredExpensesByViewType[0]?.date;
      if (date) {
        return new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
      }
      return 'Daily';
    } else if (viewType === 'weekly') {
      const dates = filteredExpensesByViewType.map(e => e.date).sort();
      if (dates.length > 0) {
        const startDate = new Date(dates[0]);
        const endDate = new Date(dates[dates.length - 1]);
        return `${startDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} - ${endDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`;
      }
      return 'Weekly';
    } else {
      const date = filteredExpensesByViewType[0]?.date;
      if (date) {
        return new Date(date).toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
      }
      return 'Monthly';
    }
  };

  // Custom tooltip for charts
  const CustomTooltip = ({ active, payload, label }: any) => {
    if (active && payload && payload.length) {
      return (
        <div className={`p-4 rounded-lg shadow-lg ${darkMode ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'} border`}>
          <p className={`text-sm font-medium mb-2 ${darkMode ? 'text-white' : 'text-gray-900'}`}>
            {viewType === 'daily' 
              ? new Date(label).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
              : viewType === 'weekly'
                ? `Week of ${new Date(label).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`
                : new Date(label + '-01').toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}
          </p>
          {payload.map((entry: any, index: number) => (
            <p key={index} className="text-sm flex items-center gap-2 my-1">
              <span 
                className="w-3 h-3 rounded-full inline-block" 
                style={{ backgroundColor: entry.color || entry.stroke }}
              />
              <span className={darkMode ? 'text-gray-300' : 'text-gray-700'}>
                {entry.name}: 
              </span>
              <span className={`font-medium ${
                entry.name === 'net' 
                  ? entry.value >= 0 ? 'text-green-500' : 'text-red-500'
                  : entry.name === 'income' ? 'text-green-500' : 'text-red-500'
              }`}>
                ${Math.abs(entry.value).toLocaleString()}
              </span>
            </p>
          ))}
        </div>
      );
    }
    return null;
  };

  const formatXAxisTick = (value: string) => {
    if (viewType === 'daily') {
      return new Date(value).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    } else if (viewType === 'weekly') {
      return `W${new Date(value).getDate() <= 7 ? '1' : new Date(value).getDate() <= 14 ? '2' : new Date(value).getDate() <= 21 ? '3' : '4'} ${new Date(value).toLocaleDateString('en-US', { month: 'short' })}`;
    } else {
      const [year, month] = value.split('-');
      return new Date(parseInt(year), parseInt(month) - 1).toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
    }
  };

  return (
    <div className={`min-h-screen flex flex-col transition-colors duration-300 ${darkMode ? 'dark bg-gray-900' : 'bg-gray-50'}`}>
      <style jsx global>{`
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap');
        * {
          font-family: 'Plus Jakarta Sans', sans-serif;
        }
      `}</style>
      
      {/* Header */}
      <header className={`sticky top-0 z-50 border-b transition-colors duration-300 ${darkMode ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'}`}>
        <div className="flex items-center justify-between px-4 py-4">
          <div className="flex items-center gap-4">
            <Button variant="ghost" size="sm" onClick={toggleSidebar} className="lg:hidden">
              <Menu className="h-5 w-5" />
            </Button>
            <div className="flex items-center gap-2">
              <Wallet className={`h-8 w-8 ${darkMode ? 'text-purple-400' : 'text-purple-600'}`} />
              <h1 className={`text-2xl font-bold ${darkMode ? 'text-white' : 'text-gray-900'}`}>
                WizardXpense
              </h1>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="ghost" size="sm" onClick={toggleDarkMode} className={`rounded-full ${darkMode ? 'text-white hover:bg-gray-700' : 'text-gray-900 hover:bg-gray-100'}`}>
              {darkMode ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
            </Button>
          </div>
        </div>
      </header>

      <div className="flex flex-1">
        {/* Sidebar */}
        <aside className={`fixed inset-y-0 left-0 z-40 w-64 transform transition-transform duration-300 lg:relative lg:translate-x-0 ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'} ${darkMode ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'} border-r`}>
          <nav className="flex-1 space-y-4 p-4 mt-20 lg:mt-4">
            <Button
              variant="secondary"
              className={`w-full justify-start gap-3 ${
                darkMode ? 'bg-purple-600 text-white hover:bg-purple-700' : 'bg-purple-100 text-purple-800 hover:bg-purple-200'
              }`}
            >
              <Home className="h-5 w-5" />
              Dashboard
            </Button>
            <div className={`mt-6 p-4 rounded-lg ${darkMode ? 'bg-gray-700' : 'bg-gray-100'}`}>
              <h3 className={`text-sm font-semibold mb-3 ${darkMode ? 'text-gray-300' : 'text-gray-600'}`}>
                Quick Stats
              </h3>
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <span className={`text-sm ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>{getPeriodLabel()}</span>
                  <span className={`text-sm font-medium ${darkMode ? 'text-gray-200' : 'text-gray-800'}`}>
                    ${summaryData.totalExpenses.toLocaleString()}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span className={`text-sm ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>Savings Rate</span>
                  <span className={`text-sm font-medium ${summaryData.savings >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                    {((summaryData.savings / (summaryData.totalIncome || 1)) * 100).toFixed(0)}%
                  </span>
                </div>
              </div>
            </div>
            <div className={`p-4 rounded-lg ${darkMode ? 'bg-gray-700' : 'bg-gray-100'}`}>
              <h3 className={`text-sm font-semibold mb-3 flex items-center gap-2 ${darkMode ? 'text-gray-300' : 'text-gray-600'}`}>
                <Target className="h-4 w-4" />
                Budget Goals
              </h3>
              <div className="space-y-3">
                {categoryData.slice(0, 3).map((category, index) => (
                  <div key={index}>
                    <div className="flex items-center justify-between mb-1">
                      <span className={`text-xs ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>{category.name}</span>
                      <span className={`text-xs ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>
                        ${category.value.toLocaleString()} / $2000
                      </span>
                    </div>
                    <div className={`w-full h-2 rounded-full ${darkMode ? 'bg-gray-600' : 'bg-gray-300'}`}>
                      <div
                        className="h-full rounded-full transition-all duration-300"
                        style={{
                          width: `${Math.min((category.value / 2000) * 100, 100)}%`,
                          backgroundColor: category.color
                        }}
                      />
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <div className={`p-4 rounded-lg ${darkMode ? 'bg-gray-700' : 'bg-gray-100'}`}>
              <h3 className={`text-sm font-semibold mb-3 flex items-center gap-2 ${darkMode ? 'text-gray-300' : 'text-gray-600'}`}>
                <Activity className="h-4 w-4" />
                Recent Activity
              </h3>
              <div className="space-y-2">
                {filteredExpensesByViewType.slice(0, 3).map((expense) => (
                  <div key={expense.id} className={`text-xs ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>
                    <div className="flex justify-between">
                      <span>{expense.category}</span>
                      <span className={expense.type === 'income' ? 'text-green-500' : 'text-red-500'}>
                        {expense.type === 'income' ? '+' : '-'}${expense.amount}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </nav>
        </aside>

        {/* Main Content */}
        <main className="flex-1 p-4 lg:p-6">
          <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex flex-col md:flex-row flex-wrap gap-4 items-start md:items-center">
              {/* Filters Section - FIXED: Better alignment and improved hover contrast */}
              <Card className={`shadow-sm border ${darkMode ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'} p-4 w-full md:w-auto`}>
                <div className="flex flex-col md:flex-row items-start md:items-center gap-4">
                  <div className="flex items-center gap-2 whitespace-nowrap">
                    <Filter className={`h-5 w-5 ${darkMode ? 'text-gray-300' : 'text-gray-700'}`} />
                    <span className={`text-sm font-medium ${darkMode ? 'text-white' : 'text-gray-900'}`}>Filter:</span>
                  </div>
                  
                  <div className="flex flex-col md:flex-row items-center gap-4 w-full">
                    {/* Improved Date Range Picker */}
                    <div className="w-full md:w-auto">
                      <DateRangePicker
                        startDate={startDate}
                        endDate={endDate}
                        onStartDateChange={setStartDate}
                        onEndDateChange={setEndDate}
                        darkMode={darkMode}
                      />
                    </div>
                    
                    {/* Improved View Type Selector */}
                    <div className="w-full md:w-auto mt-3 md:mt-0">
                      <SegmentedControl
                        options={[
                          { value: 'daily', label: 'Daily' },
                          { value: 'weekly', label: 'Weekly' },
                          { value: 'monthly', label: 'Monthly' }
                        ]}
                        value={viewType}
                        onChange={setViewType}
                        darkMode={darkMode}
                      />
                    </div>
                  </div>
                </div>
              </Card>
            </div>
          </div>

          <div className="mb-8 grid gap-4 md:grid-cols-3">
            <Card className="overflow-hidden border-0 bg-gradient-to-br from-blue-500 to-purple-600 text-white transition-transform duration-200 hover:scale-105">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">
                  {getPeriodLabel()} Expenses
                </CardTitle>
                <TrendingDown className="h-5 w-5 opacity-90" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">${summaryData.totalExpenses.toLocaleString()}</div>
              </CardContent>
            </Card>
            <Card className="overflow-hidden border-0 bg-gradient-to-br from-green-500 to-teal-600 text-white transition-transform duration-200 hover:scale-105">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">
                  {getPeriodLabel()} Income
                </CardTitle>
                <TrendingUp className="h-5 w-5 opacity-90" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">${summaryData.totalIncome.toLocaleString()}</div>
              </CardContent>
            </Card>
            <Card className="overflow-hidden border-0 bg-gradient-to-br from-orange-500 to-red-600 text-white transition-transform duration-200 hover:scale-105">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">
                  {getPeriodLabel()} Savings
                </CardTitle>
                <PiggyBank className="h-5 w-5 opacity-90" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">${summaryData.savings.toLocaleString()}</div>
              </CardContent>
            </Card>
          </div>

          {/* Charts */}
          <div className="grid gap-6 lg:grid-cols-2">
            <Card className={`transition-colors duration-300 ${darkMode ? 'bg-gray-800 border-gray-700' : 'bg-white'}`}>
              <CardHeader>
                <CardTitle className={`flex items-center gap-2 ${darkMode ? 'text-white' : 'text-gray-900'}`}>
                  <BarChart3 className="h-5 w-5" />
                  {getPeriodLabel()} Spending by Category
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-[300px]">
                  {categoryData.length > 0 ? (
                    <ResponsiveContainer width="100%" height="100%">
                      <PieChart>
                        <Pie
                          data={categoryData}
                          cx="50%"
                          cy="50%"
                          labelLine={false}
                          label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                          outerRadius={80}
                          fill="#8884d8"
                          dataKey="value"
                        >
                          {categoryData.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={entry.color} />
                          ))}
                        </Pie>
                        <Tooltip content={<CustomTooltip />} />
                      </PieChart>
                    </ResponsiveContainer>
                  ) : (
                    <div className="flex items-center justify-center h-full">
                      <p className={`text-sm ${darkMode ? 'text-gray-400' : 'text-gray-600'}`}>
                        No expenses for selected period
                      </p>
                    </div>
                  )}
                </div>
                {categoryData.length > 0 && (
                  <div className="mt-4 grid grid-cols-2 gap-3">
                    {categoryData.map((category, index) => (
                      <div key={index} className="flex items-center gap-2">
                        <div className="h-3 w-3 rounded-full" style={{ backgroundColor: category.color }} />
                        <span className={`text-sm ${darkMode ? 'text-gray-300' : 'text-gray-600'}`}>
                          {category.name} (${category.value.toLocaleString()})
                        </span>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>

            <Card className={`transition-colors duration-300 ${darkMode ? 'bg-gray-800 border-gray-700' : 'bg-white'}`}>
              <CardHeader>
                <CardTitle className={`flex items-center gap-2 ${darkMode ? 'text-white' : 'text-gray-900'}`}>
                  <TrendingUp className="h-5 w-5" />
                  Expense Trends
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="h-[350px]"> {/* Increased height for better readability */}
                  <ResponsiveContainer width="100%" height="100%">
                    <LineChart data={trendData} margin={{ top: 20, right: 30, left: 20, bottom: 60 }}>
                      <CartesianGrid strokeDasharray="3 3" stroke={darkMode ? '#374151' : '#E5E7EB'} />
                      <XAxis
                        dataKey="date"
                        tick={{ fill: darkMode ? '#9CA3AF' : '#6B7280', fontSize: 12 }}
                        angle={-45}
                        textAnchor="end"
                        height={70}
                        tickFormatter={formatXAxisTick}
                        interval={0}
                      />
                      <YAxis
                        tick={{ fill: darkMode ? '#9CA3AF' : '#6B7280', fontSize: 12 }}
                        tickFormatter={(value) => `$${(value / 1000).toFixed(0)}k`}
                      />
                      <Tooltip content={<CustomTooltip />} />
                      <Legend
                        verticalAlign="top"
                        height={36}
                        wrapperStyle={{
                          color: darkMode ? '#D1D5DB' : '#374151',
                          paddingTop: '10px'
                        }}
                      />
                      <Line
                        type="monotone"
                        dataKey="expenses"
                        name="Expenses"
                        stroke="#EF4444"
                        strokeWidth={2}
                        dot={{ r: 4 }}
                        activeDot={{ r: 6 }}
                      />
                      <Line
                        type="monotone"
                        dataKey="income"
                        name="Income"
                        stroke="#10B981"
                        strokeWidth={2}
                        dot={{ r: 4 }}
                        activeDot={{ r: 6 }}
                      />
                      <Line
                        type="monotone"
                        dataKey="net"
                        name="Net"
                        stroke="#3B82F6"
                        strokeWidth={2}
                        strokeDasharray="5 5"
                        dot={{ r: 4 }}
                        activeDot={{ r: 6 }}
                      />
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              </CardContent>
            </Card>
          </div>
        </main>
      </div>

      {/* Footer */}
      <footer className={`border-t transition-colors duration-300 ${darkMode ? 'bg-gray-800 border-gray-700 text-gray-400' : 'bg-white border-gray-200 text-gray-600'}`}>
        <div className="container mx-auto px-4 py-6">
          <div className="flex flex-col md:flex-row justify-between items-center gap-4">
            <div className="flex items-center gap-2">
              <Wallet className={`h-5 w-5 ${darkMode ? 'text-purple-400' : 'text-purple-600'}`} />
              <span className="font-semibold">WizardXpense</span>
              <span className="text-sm">© 2025</span>
            </div>
            <p className="text-sm text-center">
              Track your expenses magically. Built with ❤️ for financial wizards.
            </p>
          </div>
        </div>
      </footer>

      {sidebarOpen && (
        <div className="fixed inset-0 z-30 bg-black bg-opacity-50 lg:hidden" onClick={toggleSidebar} />
      )}
    </div>
  );
};

export default ExpenseTrackingDashboard;] remove mentioning month name in cards and spending category. 
In light mode the hamburger menu color contrast is not okay it's light that I can't see. 
Also when I open the sidebar in mobile the background of the dashboard become black which it should not it should be blurry type. 
Also remove all the comments from the code. 
Give me full code after fixing these things.