"use client"

import React from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Button } from '../ui/button'
import { Badge } from '../ui/badge'
import { Input } from '../ui/input'
import { ScrollArea } from '../ui/scroll-area'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs'
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar'
import { Separator } from '../ui/separator'
import { 
  Activity,
  Download,
  Upload,
  Settings,
  Edit3,
  Save,
  X,
  Plus,
  RefreshCw,
  Share2,
  Filter,
  LayoutGrid,
  Palette,
  Search,
  Bell,
  Menu,
  ChevronRight,
  Sparkles,
  BarChart3,
  Users,
  DollarSign,
  TrendingUp,
  Calendar,
  Map,
  Table,
  Clock,
  Target,
  ArrowUpRight,
  CheckCircle,
  User,
  LogOut,
  Settings2,
  AlertCircle,
  Info,
  CheckCheck
} from 'lucide-react'
import { cn } from '../../lib/utils'
import { DashboardGrid } from './dashboard-grid'
import { TimeRangePicker } from './time-range-picker'
import { MetricCard } from './widgets/metric-card'
import { ChartWidget } from './widgets/chart-widget'
import { ActivityFeed } from './widgets/activity-feed'
import {
  Widget,
  DashboardConfig,
  DashboardTheme,
  TimeRange,
  MetricData,
  ChartData,
  ActivityItem,
  DashboardTemplate,
  WidgetType,
  DashboardNotification
} from './types'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from '../ui/dropdown-menu'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog'
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from '../ui/sheet'

interface DashboardProps {
  config?: DashboardConfig
  widgets?: Widget[]
  templates?: DashboardTemplate[]
  onConfigChange?: (config: DashboardConfig) => void
  onWidgetAdd?: (widget: Omit<Widget, 'id'>) => void
  onWidgetRemove?: (widgetId: string) => void
  onWidgetUpdate?: (widgetId: string, updates: Partial<Widget>) => void
  onExport?: (format: 'json' | 'pdf' | 'png') => void
  onImport?: (file: File) => void
  className?: string
  showHeader?: boolean
  title?: string
  description?: string
  editable?: boolean
  realtime?: boolean
  glassmorphism?: boolean
  
  // Notification yönetimi
  notifications?: DashboardNotification[]
  onNotificationClick?: (notification: DashboardNotification) => void
  onNotificationMarkAsRead?: (notificationId: string) => void
  onNotificationMarkAllAsRead?: () => void
  onNotificationClear?: (notificationId: string) => void
  onNotificationClearAll?: () => void
  
  // User yönetimi
  user?: {
    name: string
    email?: string
    avatar?: string
    role?: string
  }
  userMenuItems?: Array<{
    id: string
    label: string
    icon?: React.ReactNode
    onClick?: () => void
    separator?: boolean
  }>
  onUserMenuClick?: () => void
  onProfileClick?: () => void
  onLogout?: () => void
  
  // Header actions
  onSearch?: (query: string) => void
  onThemeChange?: (theme: DashboardTheme) => void
  onMenuClick?: () => void
  onRefresh?: () => void
  
  // Custom header actions
  headerActions?: React.ReactNode
  
  // Time range yönetimi
  timeRange?: TimeRange
  onTimeRangeChange?: (range: TimeRange) => void
  
  // Custom branding
  logo?: React.ReactNode
  brandName?: string
}

// Dashboard template'leri
const DASHBOARD_TEMPLATES: DashboardTemplate[] = [
  {
    id: 'analytics',
    name: 'Analytics Dashboard',
    description: 'Comprehensive analytics with metrics and charts',
    category: 'analytics',
    theme: 'analytics',
    widgets: [
      {
        type: 'metric',
        title: 'Total Revenue',
        size: { w: 3, h: 2 },
        position: { x: 0, y: 0 },
        data: {
          id: 'revenue',
          title: 'Total Revenue',
          value: 125430,
          change: { value: 12, type: 'increase', period: 'last month' },
          color: 'success',
          icon: <DollarSign className="h-4 w-4" />,
          sparkline: [100, 120, 115, 125, 130, 128, 132],
          unit: '$'
        }
      },
      {
        type: 'metric',
        title: 'Active Users',
        size: { w: 3, h: 2 },
        position: { x: 3, y: 0 },
        data: {
          id: 'users',
          title: 'Active Users',
          value: 2543,
          change: { value: 8, type: 'increase', period: 'last week' },
          color: 'primary',
          icon: <Users className="h-4 w-4" />,
          sparkline: [200, 220, 210, 230, 225, 240, 254]
        }
      },
      {
        type: 'chart',
        title: 'Revenue Trend',
        size: { w: 6, h: 4 },
        position: { x: 0, y: 2 },
        data: {
          type: 'area',
          data: [
            { name: 'Jan', revenue: 4000, profit: 2400 },
            { name: 'Feb', revenue: 3000, profit: 1398 },
            { name: 'Mar', revenue: 5000, profit: 3200 },
            { name: 'Apr', revenue: 4500, profit: 2900 },
            { name: 'May', revenue: 6000, profit: 3800 },
            { name: 'Jun', revenue: 5500, profit: 3400 }
          ]
        }
      },
      {
        type: 'activity',
        title: 'Recent Activity',
        size: { w: 3, h: 6 },
        position: { x: 9, y: 0 },
        data: {
          realtime: true,
          items: [
            {
              id: '1',
              type: 'success',
              title: 'completed a purchase',
              description: 'Order #12345 - $250.00',
              timestamp: new Date(Date.now() - 1000 * 60 * 5),
              user: { name: 'John Doe' }
            },
            {
              id: '2',
              type: 'info',
              title: 'signed up',
              description: 'New user registration',
              timestamp: new Date(Date.now() - 1000 * 60 * 15),
              user: { name: 'Jane Smith' }
            }
          ]
        }
      }
    ]
  },
  {
    id: 'sales',
    name: 'Sales Dashboard',
    description: 'Track sales performance and targets',
    category: 'sales',
    theme: 'sales',
    widgets: [
      // Sales-specific widgets
    ]
  },
  {
    id: 'monitoring',
    name: 'System Monitoring',
    description: 'Monitor system health and performance',
    category: 'operations',
    theme: 'monitoring',
    widgets: [
      // Monitoring widgets
    ]
  }
]

// Widget türleri için ikonlar
const WIDGET_TYPE_ICONS: Record<WidgetType, React.ReactNode> = {
  metric: <BarChart3 className="h-4 w-4" />,
  chart: <Activity className="h-4 w-4" />,
  table: <Table className="h-4 w-4" />,
  map: <Map className="h-4 w-4" />,
  activity: <Clock className="h-4 w-4" />,
  calendar: <Calendar className="h-4 w-4" />,
  progress: <Target className="h-4 w-4" />,
  comparison: <TrendingUp className="h-4 w-4" />
}

// Tema renkleri
const THEME_COLORS: Record<DashboardTheme, string> = {
  analytics: 'from-blue-500/10 to-purple-500/10',
  sales: 'from-green-500/10 to-emerald-500/10',
  monitoring: 'from-orange-500/10 to-red-500/10',
  finance: 'from-indigo-500/10 to-blue-500/10',
  custom: 'from-gray-500/10 to-gray-600/10'
}

// Relative time formatter
function formatRelativeTime(date: Date): string {
  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
  
  if (diffInSeconds < 60) return 'just now';
  if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}m ago`;
  if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}h ago`;
  if (diffInSeconds < 604800) return `${Math.floor(diffInSeconds / 86400)}d ago`;
  
  return date.toLocaleDateString();
}

export function Dashboard({
  config,
  widgets: initialWidgets = [],
  templates = DASHBOARD_TEMPLATES,
  onConfigChange,
  onWidgetAdd,
  onWidgetRemove,
  onWidgetUpdate,
  onExport,
  onImport,
  className,
  showHeader = true,
  title = 'Dashboard',
  description = 'Real-time analytics and insights',
  editable = true,
  realtime = false,
  glassmorphism = true,
  notifications = [],
  onNotificationClick,
  onNotificationMarkAsRead,
  onNotificationMarkAllAsRead,
  onNotificationClear,
  onNotificationClearAll,
  user,
  userMenuItems,
  onUserMenuClick,
  onProfileClick,
  onLogout,
  onSearch,
  onThemeChange,
  onMenuClick,
  onRefresh,
  headerActions,
  timeRange: propTimeRange,
  onTimeRangeChange,
  logo,
  brandName
}: DashboardProps) {
  // State yönetimi
  const [editMode, setEditMode] = React.useState(false)
  const [widgets, setWidgets] = React.useState<Widget[]>(initialWidgets)
  const [selectedTheme, setSelectedTheme] = React.useState<DashboardTheme>('analytics')
  const [timeRange, setTimeRange] = React.useState<TimeRange | undefined>(propTimeRange)
  const [searchQuery, setSearchQuery] = React.useState('')
  const [showWidgetLibrary, setShowWidgetLibrary] = React.useState(false)
  const [showTemplates, setShowTemplates] = React.useState(false)
  const [refreshing, setRefreshing] = React.useState(false)
  const [showNotifications, setShowNotifications] = React.useState(false)

  // initialWidgets değiştiğinde state'i güncelle
  React.useEffect(() => {
    setWidgets(initialWidgets)
  }, [initialWidgets])

  // propTimeRange değiştiğinde state'i güncelle
  React.useEffect(() => {
    if (propTimeRange) {
      setTimeRange(propTimeRange)
    }
  }, [propTimeRange])

  // WebSocket bağlantısı (real-time için)
  React.useEffect(() => {
    if (!realtime) return

    // Simüle edilmiş WebSocket bağlantısı
    const interval = setInterval(() => {
      // Widget'ları güncelle
      setWidgets(prev => prev.map(widget => {
        if (widget.type === 'metric' && widget.data) {
          const newValue = typeof widget.data.value === 'number' 
            ? widget.data.value + Math.floor(Math.random() * 10 - 5)
            : widget.data.value
          
          return {
            ...widget,
            data: {
              ...widget.data,
              value: newValue,
              lastUpdated: new Date()
            }
          }
        }
        return widget
      }))
    }, 5000)

    return () => clearInterval(interval)
  }, [realtime])

  // Widget ekle
  const handleAddWidget = (type: WidgetType) => {
    const newWidget: Widget = {
      id: `widget-${Date.now()}`,
      type,
      title: `New ${type} Widget`,
      size: { w: 3, h: 3 },
      position: { x: 0, y: 0 },
      data: generateDefaultData(type)
    }

    setWidgets(prev => [...prev, newWidget])
    onWidgetAdd?.(newWidget)
    setShowWidgetLibrary(false)
  }

  // Template uygula
  const applyTemplate = (template: DashboardTemplate) => {
    const newWidgets = template.widgets.map((w, index) => ({
      ...w,
      id: `widget-${Date.now()}-${index}`,
      position: w.position || { x: (index * 3) % 12, y: Math.floor((index * 3) / 12) * 3 },
      size: w.size || { w: 3, h: 3 }
    }))
    
    setWidgets(newWidgets as Widget[])
    setSelectedTheme(template.theme)
    setShowTemplates(false)
  }

  // Varsayılan widget verisi oluştur
  const generateDefaultData = (type: WidgetType): any => {
    switch (type) {
      case 'metric':
        return {
          id: 'new-metric',
          title: 'New Metric',
          value: 0,
          icon: <BarChart3 className="h-4 w-4" />,
          color: 'primary'
        }
      case 'chart':
        return {
          type: 'line',
          data: [
            { name: 'Mon', value: 100 },
            { name: 'Tue', value: 120 },
            { name: 'Wed', value: 110 },
            { name: 'Thu', value: 130 },
            { name: 'Fri', value: 125 }
          ]
        }
      case 'activity':
        return {
          items: [],
          realtime: true
        }
      default:
        return {}
    }
  }

  // Widget kütüphanesi
  const WidgetLibrary = () => (
    <Sheet open={showWidgetLibrary} onOpenChange={setShowWidgetLibrary}>
      <SheetContent className={cn(
        "w-[400px] sm:w-[540px]",
        glassmorphism && "bg-background/95 backdrop-blur-md"
      )}>
        <SheetHeader>
          <SheetTitle>Widget Library</SheetTitle>
          <SheetDescription>
            Add widgets to customize your dashboard
          </SheetDescription>
        </SheetHeader>
        
        <div className="mt-6 space-y-4">
          <div className="relative">
            <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="Search widgets..."
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                onSearch?.(e.target.value);
              }}
              className="pl-10"
            />
          </div>

          <ScrollArea className="h-[calc(100vh-200px)]">
            <div className="grid grid-cols-2 gap-4">
              {Object.entries(WIDGET_TYPE_ICONS)
                .filter(([type]) => type.toLowerCase().includes(searchQuery.toLowerCase()))
                .map(([type, icon]) => (
                  <motion.div
                    key={type}
                    whileHover={{ scale: 1.02 }}
                    whileTap={{ scale: 0.98 }}
                  >
                    <Button
                      variant="outline"
                      className="w-full h-24 flex-col gap-2"
                      onClick={() => handleAddWidget(type as WidgetType)}
                    >
                      <div className="p-2 rounded-lg bg-muted">
                        {icon}
                      </div>
                      <span className="capitalize text-sm">{type}</span>
                    </Button>
                  </motion.div>
                ))}
            </div>
          </ScrollArea>
        </div>
      </SheetContent>
    </Sheet>
  )

  // Template galerisi
  const TemplateGallery = () => (
    <Dialog open={showTemplates} onOpenChange={setShowTemplates}>
      <DialogContent className={cn(
        "max-w-4xl",
        glassmorphism && "bg-background/95 backdrop-blur-md"
      )}>
        <DialogHeader>
          <DialogTitle>Dashboard Templates</DialogTitle>
          <DialogDescription>
            Start with a pre-built template or create your own
          </DialogDescription>
        </DialogHeader>

        <Tabs defaultValue="all" className="mt-4">
          <TabsList>
            <TabsTrigger value="all">All Templates</TabsTrigger>
            <TabsTrigger value="analytics">Analytics</TabsTrigger>
            <TabsTrigger value="sales">Sales</TabsTrigger>
            <TabsTrigger value="operations">Operations</TabsTrigger>
          </TabsList>

          <TabsContent value="all" className="mt-4">
            <div className="grid grid-cols-3 gap-4">
              {templates.map((template) => (
                <motion.div
                  key={template.id}
                  whileHover={{ y: -4 }}
                  className="cursor-pointer"
                  onClick={() => applyTemplate(template)}
                >
                  <div className={cn(
                    "relative overflow-hidden rounded-lg border p-4 hover:shadow-lg transition-all",
                    "bg-gradient-to-br", THEME_COLORS[template.theme]
                  )}>
                    {template.isPro && (
                      <Badge className="absolute top-2 right-2" variant="secondary">
                        PRO
                      </Badge>
                    )}
                    <h3 className="font-semibold mb-1">{template.name}</h3>
                    <p className="text-sm text-muted-foreground">
                      {template.description}
                    </p>
                    <div className="mt-3 flex items-center gap-2 text-xs text-muted-foreground">
                      <span>{template.widgets.length} widgets</span>
                      <span>•</span>
                      <span className="capitalize">{template.category}</span>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  )

  return (
    <motion.div 
      className={cn(
        "w-full min-h-screen",
        glassmorphism && "bg-gradient-to-br", 
        glassmorphism && THEME_COLORS[selectedTheme],
        className
      )}
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.5 }}
    >
      {/* Header */}
      {showHeader && (
        <motion.div 
          className={cn(
            "sticky top-0 z-30 border-b",
            glassmorphism ? "bg-background/80 backdrop-blur-md" : "bg-background"
          )}
          initial={{ y: -50 }}
          animate={{ y: 0 }}
          transition={{ type: "spring", stiffness: 300, damping: 30 }}
        >
          <div className="px-6 py-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <motion.div
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <Button 
                    variant="ghost" 
                    size="sm" 
                    className="lg:hidden"
                    onClick={onMenuClick}
                  >
                    <Menu className="h-5 w-5" />
                  </Button>
                </motion.div>
                
                {/* Logo and Brand */}
                {(logo || brandName) && (
                  <div className="flex items-center gap-2">
                    {logo}
                    {brandName && (
                      <span className="font-semibold text-lg">{brandName}</span>
                    )}
                  </div>
                )}
                
                <div>
                  <div className="flex items-center gap-2">
                    <h1 className="text-2xl font-bold tracking-tight">{title}</h1>
                    {realtime && (
                      <Badge variant="secondary" className="animate-pulse">
                        <span className="mr-1 h-1.5 w-1.5 rounded-full bg-green-500" />
                        Real-time
                      </Badge>
                    )}
                  </div>
                  <p className="text-sm text-muted-foreground">{description}</p>
                </div>
              </div>

              {/* Header actions */}
              <div className="flex items-center gap-2">
                {/* Time range picker */}
                <TimeRangePicker
                  value={timeRange}
                  onChange={(range) => {
                    setTimeRange(range);
                    onTimeRangeChange?.(range);
                  }}
                  glassmorphism={glassmorphism}
                />

                {/* Notifications */}
                <DropdownMenu open={showNotifications} onOpenChange={setShowNotifications}>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" size="sm" className="relative h-9 w-9 p-0">
                      <Bell className="h-5 w-5" />
                      {notifications.filter(n => !n.read).length > 0 && (
                        <span className="absolute -top-1 -right-1 min-w-[1rem] h-4 px-1 rounded-full bg-destructive text-[10px] font-medium text-destructive-foreground flex items-center justify-center">
                          {notifications.filter(n => !n.read).length}
                        </span>
                      )}
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent 
                    align="end" 
                    className="w-80"
                    sideOffset={8}
                  >
                    <div className="flex items-center justify-between px-4 py-2">
                      <h4 className="text-sm font-semibold">Notifications</h4>
                      {notifications.length > 0 && (
                        <div className="flex items-center gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-auto p-1 text-xs"
                            onClick={() => onNotificationMarkAllAsRead?.()}
                          >
                            <CheckCheck className="h-3 w-3 mr-1" />
                            Mark all read
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-auto p-1 text-xs"
                            onClick={() => onNotificationClearAll?.()}
                          >
                            Clear all
                          </Button>
                        </div>
                      )}
                    </div>
                    <Separator />
                    <ScrollArea className="h-[400px]">
                      {notifications.length === 0 ? (
                        <div className="p-8 text-center text-sm text-muted-foreground">
                          <Bell className="h-8 w-8 mx-auto mb-2 opacity-20" />
                          <p>No notifications</p>
                        </div>
                      ) : (
                        <div className="p-1">
                          {notifications.map((notification) => {
                            const Icon = notification.type === 'error' ? AlertCircle :
                                       notification.type === 'warning' ? AlertCircle :
                                       notification.type === 'success' ? CheckCircle :
                                       Info;
                            
                            return (
                              <motion.div
                                key={notification.id}
                                initial={{ opacity: 0, x: -20 }}
                                animate={{ opacity: 1, x: 0 }}
                                className={cn(
                                  "flex items-start gap-3 p-3 rounded-lg cursor-pointer transition-colors",
                                  "hover:bg-muted/50",
                                  !notification.read && "bg-muted/30"
                                )}
                                onClick={() => {
                                  onNotificationClick?.(notification);
                                  if (!notification.read) {
                                    onNotificationMarkAsRead?.(notification.id);
                                  }
                                }}
                              >
                                <div className={cn(
                                  "mt-0.5 p-1.5 rounded-full",
                                  notification.type === 'error' && "bg-destructive/10 text-destructive",
                                  notification.type === 'warning' && "bg-yellow-500/10 text-yellow-600 dark:text-yellow-500",
                                  notification.type === 'success' && "bg-green-500/10 text-green-600 dark:text-green-500",
                                  notification.type === 'info' && "bg-blue-500/10 text-blue-600 dark:text-blue-500"
                                )}>
                                  <Icon className="h-3.5 w-3.5" />
                                </div>
                                <div className="flex-1 space-y-1">
                                  <p className="text-sm font-medium leading-none">
                                    {notification.title}
                                  </p>
                                  {notification.message && (
                                    <p className="text-xs text-muted-foreground">
                                      {notification.message}
                                    </p>
                                  )}
                                  <p className="text-xs text-muted-foreground">
                                    {formatRelativeTime(notification.timestamp)}
                                  </p>
                                </div>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-6 w-6 p-0"
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    onNotificationClear?.(notification.id);
                                  }}
                                >
                                  <X className="h-3 w-3" />
                                </Button>
                              </motion.div>
                            );
                          })}
                        </div>
                      )}
                    </ScrollArea>
                  </DropdownMenuContent>
                </DropdownMenu>

                {/* Theme selector */}
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" size="sm">
                      <Palette className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem onClick={() => {
                      setSelectedTheme('analytics');
                      onThemeChange?.('analytics');
                    }}>
                      <div className="flex items-center gap-2">
                        <div className="h-4 w-4 rounded bg-gradient-to-br from-blue-500 to-purple-500" />
                        Analytics
                      </div>
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => {
                      setSelectedTheme('sales');
                      onThemeChange?.('sales');
                    }}>
                      <div className="flex items-center gap-2">
                        <div className="h-4 w-4 rounded bg-gradient-to-br from-green-500 to-emerald-500" />
                        Sales
                      </div>
                    </DropdownMenuItem>
                    <DropdownMenuItem onClick={() => {
                      setSelectedTheme('monitoring');
                      onThemeChange?.('monitoring');
                    }}>
                      <div className="flex items-center gap-2">
                        <div className="h-4 w-4 rounded bg-gradient-to-br from-orange-500 to-red-500" />
                        Monitoring
                      </div>
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>

                {/* Custom header actions */}
                {headerActions}

                {/* User Profile */}
                {user && (
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="sm" className="relative h-8 w-8 rounded-full">
                        <Avatar className="h-8 w-8">
                          <AvatarImage src={user.avatar} alt={user.name} />
                          <AvatarFallback>
                            {user.name.split(' ').map(n => n[0]).join('').toUpperCase()}
                          </AvatarFallback>
                        </Avatar>
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end" className="w-56">
                      <div className="flex items-center justify-start gap-2 p-2">
                        <div className="flex flex-col space-y-1 leading-none">
                          {user.name && (
                            <p className="font-medium">{user.name}</p>
                          )}
                          {user.email && (
                            <p className="text-xs text-muted-foreground">
                              {user.email}
                            </p>
                          )}
                        </div>
                      </div>
                      <DropdownMenuSeparator />
                      {userMenuItems ? (
                        // Custom menu items
                        userMenuItems.map((item, index) => (
                          item.separator ? (
                            <DropdownMenuSeparator key={item.id || `sep-${index}`} />
                          ) : (
                            <DropdownMenuItem 
                              key={item.id}
                              onClick={() => item.onClick?.()}
                            >
                              {item.icon && <span className="mr-2">{item.icon}</span>}
                              {item.label}
                            </DropdownMenuItem>
                          )
                        ))
                      ) : (
                        // Default menu items
                        <>
                          <DropdownMenuItem onClick={() => onProfileClick?.()}>
                            <User className="mr-2 h-4 w-4" />
                            Profile
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => onUserMenuClick?.()}>
                            <Settings2 className="mr-2 h-4 w-4" />
                            Settings
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem onClick={() => onLogout?.()}>
                            <LogOut className="mr-2 h-4 w-4" />
                            Log out
                          </DropdownMenuItem>
                        </>
                      )}
                    </DropdownMenuContent>
                  </DropdownMenu>
                )}

                {/* More actions */}
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="outline" size="sm">
                      <Settings className="h-4 w-4 mr-2" />
                      Actions
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end" className="w-48">
                    {editable && (
                      <>
                        <DropdownMenuItem onClick={() => setEditMode(!editMode)}>
                          <Edit3 className="mr-2 h-4 w-4" />
                          {editMode ? 'Exit Edit Mode' : 'Edit Layout'}
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => setShowWidgetLibrary(true)}>
                          <Plus className="mr-2 h-4 w-4" />
                          Add Widget
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => setShowTemplates(true)}>
                          <LayoutGrid className="mr-2 h-4 w-4" />
                          Templates
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                      </>
                    )}
                    
                    <DropdownMenuSub>
                      <DropdownMenuSubTrigger>
                        <Download className="mr-2 h-4 w-4" />
                        Export
                      </DropdownMenuSubTrigger>
                      <DropdownMenuSubContent>
                        <DropdownMenuItem onClick={() => onExport?.('json')}>
                          As JSON
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => onExport?.('pdf')}>
                          As PDF
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => onExport?.('png')}>
                          As Image
                        </DropdownMenuItem>
                      </DropdownMenuSubContent>
                    </DropdownMenuSub>
                    
                    <DropdownMenuItem>
                      <Upload className="mr-2 h-4 w-4" />
                      Import
                    </DropdownMenuItem>
                    
                    <DropdownMenuSeparator />
                    
                    <DropdownMenuItem onClick={() => {
                      setRefreshing(true);
                      onRefresh?.();
                      setTimeout(() => setRefreshing(false), 1000);
                    }}>
                      <RefreshCw className="mr-2 h-4 w-4" />
                      Refresh Data
                    </DropdownMenuItem>
                    
                    <DropdownMenuItem>
                      <Share2 className="mr-2 h-4 w-4" />
                      Share Dashboard
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            </div>
          </div>

          {/* Edit mode banner */}
          <AnimatePresence>
            {editMode && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: "auto", opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                className="bg-primary/10 border-t border-primary/20"
              >
                <div className="px-6 py-2 flex items-center justify-between">
                  <div className="flex items-center gap-2 text-sm">
                    <Sparkles className="h-4 w-4 text-primary" />
                    <span>Edit mode enabled - Drag widgets to rearrange</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setEditMode(false)}
                    >
                      <X className="h-4 w-4 mr-1" />
                      Cancel
                    </Button>
                    <Button
                      variant="primary"
                      size="sm"
                      onClick={() => {
                        setEditMode(false)
                        // Save layout changes
                      }}
                    >
                      <Save className="h-4 w-4 mr-1" />
                      Save Changes
                    </Button>
                  </div>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </motion.div>
      )}

      {/* Main content */}
      <div className="p-6">
        {widgets.length === 0 ? (
          // Empty state
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="flex flex-col items-center justify-center min-h-[400px] text-center"
          >
            <div className={cn(
              "p-4 rounded-full mb-4",
              glassmorphism ? "bg-background/60 backdrop-blur-sm" : "bg-muted"
            )}>
              <LayoutGrid className="h-8 w-8 text-muted-foreground" />
            </div>
            <h3 className="text-lg font-semibold mb-2">No widgets added yet</h3>
            <p className="text-muted-foreground mb-4">
              Start by adding widgets or choosing a template
            </p>
            <div className="flex gap-2">
              <Button onClick={() => setShowWidgetLibrary(true)}>
                <Plus className="h-4 w-4 mr-2" />
                Add Widget
              </Button>
              <Button variant="outline" onClick={() => setShowTemplates(true)}>
                <LayoutGrid className="h-4 w-4 mr-2" />
                Browse Templates
              </Button>
            </div>
          </motion.div>
        ) : (
          // Dashboard grid
          <DashboardGrid
            widgets={widgets}
            onLayoutChange={(layout) => {
              // Update widget positions
              const updatedWidgets = widgets.map(widget => {
                const layoutItem = layout.find(l => l.i === widget.id)
                if (layoutItem) {
                  return {
                    ...widget,
                    position: { x: layoutItem.x, y: layoutItem.y },
                    size: { ...widget.size, w: layoutItem.w, h: layoutItem.h }
                  }
                }
                return widget
              })
              setWidgets(updatedWidgets)
            }}
            onWidgetRemove={(widgetId) => {
              setWidgets(prev => prev.filter(w => w.id !== widgetId))
              onWidgetRemove?.(widgetId)
            }}
            onWidgetAction={(widgetId, action, data) => {
              console.log('Widget action:', widgetId, action, data)
              // Handle widget actions
            }}
            editMode={editMode}
            glassmorphism={glassmorphism}
          />
        )}
      </div>

      {/* Modals */}
      <WidgetLibrary />
      <TemplateGallery />
    </motion.div>
  )
}

export type { Widget, MetricData, ChartData, ActivityItem, ProgressData, ComparisonData } from './types'
export default Dashboard