"use client"

import React from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Card, CardContent, CardHeader, CardTitle } from '../../ui/card'
import { Button } from '../../ui/button'
import { Avatar, AvatarFallback, AvatarImage } from '../../ui/avatar'
import { Badge } from '../../ui/badge'
import { cn } from '../../../lib/utils'
import {
  Activity,
  Info,
  CheckCircle,
  AlertCircle,
  XCircle,
  Clock,
  MoreHorizontal,
  Filter,
  RefreshCw,
  Bell,
  BellOff
} from 'lucide-react'
import { ActivityItem } from '../types'
import { formatDistanceToNow } from 'date-fns'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '../../ui/dropdown-menu'
import { ScrollArea } from '../../ui/scroll-area'

interface ActivityFeedProps {
  items: ActivityItem[]
  title?: string
  className?: string
  height?: number
  onItemClick?: (item: ActivityItem) => void
  onAction?: (action: string, data?: any) => void
  loading?: boolean
  showFilters?: boolean
  showNotifications?: boolean
  glassmorphism?: boolean
  realtime?: boolean
}

export function ActivityFeed({
  items,
  title = "Activity Feed",
  className,
  height = 400,
  onItemClick,
  onAction,
  loading = false,
  showFilters = true,
  showNotifications = true,
  glassmorphism = false,
  realtime = false
}: ActivityFeedProps) {
  const [filter, setFilter] = React.useState<'all' | 'info' | 'success' | 'warning' | 'error'>('all')
  const [notificationsEnabled, setNotificationsEnabled] = React.useState(true)
  const [newItems, setNewItems] = React.useState<ActivityItem[]>([])

  // Simüle edilmiş real-time güncellemeler
  React.useEffect(() => {
    if (!realtime) return

    const interval = setInterval(() => {
      const randomItem: ActivityItem = {
        id: `new-${Date.now()}`,
        type: ['info', 'success', 'warning', 'error'][Math.floor(Math.random() * 4)] as any,
        title: 'New activity',
        description: 'Something happened just now',
        timestamp: new Date(),
        user: {
          name: 'System',
          avatar: undefined
        }
      }
      
      setNewItems(prev => [randomItem, ...prev].slice(0, 3))
      
      setTimeout(() => {
        setNewItems(prev => prev.filter(item => item.id !== randomItem.id))
      }, 5000)
    }, 10000)

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

  // Tip ikonları
  const getTypeIcon = (type: ActivityItem['type']) => {
    switch (type) {
      case 'info':
        return <Info className="h-4 w-4" />
      case 'success':
        return <CheckCircle className="h-4 w-4" />
      case 'warning':
        return <AlertCircle className="h-4 w-4" />
      case 'error':
        return <XCircle className="h-4 w-4" />
    }
  }

  // Tip renkleri
  const getTypeColor = (type: ActivityItem['type']) => {
    switch (type) {
      case 'info':
        return 'text-blue-500 bg-blue-100 dark:bg-blue-900/20'
      case 'success':
        return 'text-green-500 bg-green-100 dark:bg-green-900/20'
      case 'warning':
        return 'text-yellow-500 bg-yellow-100 dark:bg-yellow-900/20'
      case 'error':
        return 'text-red-500 bg-red-100 dark:bg-red-900/20'
    }
  }

  // Filtrelenmiş öğeler
  const filteredItems = [...newItems, ...items].filter(item => 
    filter === 'all' || item.type === filter
  )

  // Activity item renderer
  const renderActivityItem = (item: ActivityItem, isNew: boolean = false) => (
    <motion.div
      key={item.id}
      layout
      initial={{ opacity: 0, x: -20 }}
      animate={{ opacity: 1, x: 0 }}
      exit={{ opacity: 0, x: 20 }}
      whileHover={{ x: 4 }}
      transition={{ duration: 0.2 }}
      className={cn(
        "group relative flex gap-3 p-3 rounded-lg cursor-pointer transition-colors",
        "hover:bg-muted/50",
        isNew && "bg-primary/5 border-l-2 border-primary"
      )}
      onClick={() => onItemClick?.(item)}
    >
      {/* Timeline çizgisi */}
      <div className="absolute left-7 top-12 bottom-0 w-px bg-border" />

      {/* İkon veya Avatar */}
      <div className="relative z-10 flex-shrink-0">
        {item.user?.avatar ? (
          <Avatar className="h-8 w-8">
            <AvatarImage src={item.user.avatar} />
            <AvatarFallback>{item.user.name[0]}</AvatarFallback>
          </Avatar>
        ) : (
          <div className={cn(
            "h-8 w-8 rounded-full flex items-center justify-center",
            getTypeColor(item.type)
          )}>
            {item.icon || getTypeIcon(item.type)}
          </div>
        )}
      </div>

      {/* İçerik */}
      <div className="flex-1 min-w-0">
        <div className="flex items-start justify-between gap-2">
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium leading-tight">
              {item.user?.name && (
                <span className="text-foreground">{item.user.name} </span>
              )}
              <span className="text-muted-foreground">{item.title}</span>
            </p>
            {item.description && (
              <p className="text-sm text-muted-foreground mt-0.5 line-clamp-2">
                {item.description}
              </p>
            )}
          </div>
          
          {/* Zaman damgası */}
          <div className="flex items-center gap-1 text-xs text-muted-foreground whitespace-nowrap">
            <Clock className="h-3 w-3" />
            {formatDistanceToNow(item.timestamp, { addSuffix: true })}
          </div>
        </div>

        {/* Yeni öğe badge'i */}
        {isNew && (
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            className="inline-block mt-1"
          >
            <Badge variant="secondary" className="text-xs">New</Badge>
          </motion.div>
        )}
      </div>

      {/* Hover aksiyonları */}
      <div className="opacity-0 group-hover:opacity-100 transition-opacity">
        <Button
          variant="ghost"
          size="sm"
          className="h-6 w-6 p-0"
          onClick={(e) => {
            e.stopPropagation()
            onAction?.('more', item)
          }}
        >
          <MoreHorizontal className="h-3 w-3" />
        </Button>
      </div>
    </motion.div>
  )

  return (
    <Card className={cn(
      "relative overflow-hidden",
      glassmorphism && "bg-background/60 backdrop-blur-md border-white/10",
      className
    )}>
      {/* Header */}
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-3">
        <div className="flex items-center gap-2">
          <Activity className="h-4 w-4 text-muted-foreground" />
          <CardTitle className="text-base font-semibold">{title}</CardTitle>
          {realtime && (
            <Badge variant="secondary" className="text-xs">
              <span className="mr-1 h-1.5 w-1.5 rounded-full bg-green-500 animate-pulse" />
              Live
            </Badge>
          )}
        </div>

        {/* Aksiyonlar */}
        <div className="flex items-center gap-1">
          {showFilters && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="sm" className="h-8 px-2">
                  <Filter className="h-4 w-4 mr-1" />
                  {filter !== 'all' && <Badge variant="secondary" className="ml-1">{filter}</Badge>}
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => setFilter('all')}>
                  All Activities
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => setFilter('info')}>
                  <Info className="mr-2 h-4 w-4 text-blue-500" />
                  Information
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setFilter('success')}>
                  <CheckCircle className="mr-2 h-4 w-4 text-green-500" />
                  Success
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setFilter('warning')}>
                  <AlertCircle className="mr-2 h-4 w-4 text-yellow-500" />
                  Warning
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setFilter('error')}>
                  <XCircle className="mr-2 h-4 w-4 text-red-500" />
                  Error
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          )}

          {showNotifications && (
            <Button
              variant="ghost"
              size="sm"
              className="h-8 w-8 p-0"
              onClick={() => {
                setNotificationsEnabled(!notificationsEnabled)
                onAction?.('notifications', { enabled: !notificationsEnabled })
              }}
            >
              {notificationsEnabled ? (
                <Bell className="h-4 w-4" />
              ) : (
                <BellOff className="h-4 w-4 text-muted-foreground" />
              )}
            </Button>
          )}

          <Button
            variant="ghost"
            size="sm"
            className="h-8 w-8 p-0"
            onClick={() => onAction?.('refresh')}
          >
            <RefreshCw className="h-4 w-4" />
          </Button>
        </div>
      </CardHeader>

      {/* İçerik */}
      <CardContent className="p-0">
        <ScrollArea className="px-4 pb-4" style={{ height }}>
          <AnimatePresence mode="popLayout">
            {loading ? (
              <motion.div
                key="loading"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="space-y-3"
              >
                {[...Array(5)].map((_, i) => (
                  <div key={i} className="flex gap-3">
                    <div className="h-8 w-8 rounded-full bg-muted animate-pulse" />
                    <div className="flex-1 space-y-2">
                      <div className="h-4 bg-muted rounded animate-pulse" />
                      <div className="h-3 bg-muted rounded w-3/4 animate-pulse" />
                    </div>
                  </div>
                ))}
              </motion.div>
            ) : filteredItems.length === 0 ? (
              <motion.div
                key="empty"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="flex flex-col items-center justify-center py-12 text-muted-foreground"
              >
                <Activity className="h-8 w-8 mb-2" />
                <p className="text-sm">No activities to show</p>
              </motion.div>
            ) : (
              <div className="space-y-1">
                {filteredItems.map(item => 
                  renderActivityItem(item, newItems.some(newItem => newItem.id === item.id))
                )}
              </div>
            )}
          </AnimatePresence>
        </ScrollArea>
      </CardContent>
    </Card>
  )
}

export default ActivityFeed