'use client';

import { useTranslations } from 'next-intl';
import { useState, useEffect } from 'react';
import { formatDistanceToNow } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { motion } from 'framer-motion';
import { Activity, User, FileText, CheckCircle, AlertCircle, type LucideIcon } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { WidgetContainer } from '../widget-container';

export type ActivityType = 'user' | 'document' | 'task' | 'alert' | 'system';

export interface ActivityItem {
  id: string;
  type: ActivityType;
  title: string;
  description?: string;
  timestamp: Date;
  user?: {
    name: string;
    image?: string;
  };
  icon?: LucideIcon;
  iconColor?: string;
}

interface ActivityWidgetProps {
  id: string;
  activities?: ActivityItem[];
  isLoading?: boolean;
  isEditing?: boolean;
  onRemove?: () => void;
  locale?: string;
  maxItems?: number;
  className?: string;
}

/**
 * Get icon for activity type
 */
function getActivityIcon(type: ActivityType): LucideIcon {
  switch (type) {
    case 'user':
      return User;
    case 'document':
      return FileText;
    case 'task':
      return CheckCircle;
    case 'alert':
      return AlertCircle;
    default:
      return Activity;
  }
}

/**
 * Get color for activity type
 */
function getActivityColor(type: ActivityType): string {
  switch (type) {
    case 'user':
      return 'text-blue-500';
    case 'document':
      return 'text-purple-500';
    case 'task':
      return 'text-green-500';
    case 'alert':
      return 'text-red-500';
    default:
      return 'text-muted-foreground';
  }
}

// Sample activities for demonstration
const SAMPLE_ACTIVITIES: ActivityItem[] = [
  {
    id: '1',
    type: 'task',
    title: '3S-Audit abgeschlossen',
    description: 'Abteilung Lager - Status: Bestanden',
    timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000), // 2 hours ago
    user: { name: 'Anna Mueller' },
  },
  {
    id: '2',
    type: 'user',
    title: 'Neuer Mitarbeiter',
    description: 'Max Mustermann wurde dem Team hinzugefuegt',
    timestamp: new Date(Date.now() - 5 * 60 * 60 * 1000), // 5 hours ago
    user: { name: 'HR System' },
  },
  {
    id: '3',
    type: 'document',
    title: 'Urlaubsantrag genehmigt',
    description: 'Ihr Antrag fuer 15.-19. Januar wurde genehmigt',
    timestamp: new Date(Date.now() - 24 * 60 * 60 * 1000), // Yesterday
    user: { name: 'Maria Schmidt' },
  },
  {
    id: '4',
    type: 'alert',
    title: 'Systemwartung geplant',
    description: 'Am Samstag von 02:00 - 04:00 Uhr',
    timestamp: new Date(Date.now() - 48 * 60 * 60 * 1000), // 2 days ago
  },
];

/**
 * Activity Widget - Displays recent activities/events
 */
export function ActivityWidget({
  id,
  activities = SAMPLE_ACTIVITIES,
  isLoading = false,
  isEditing = false,
  onRemove,
  locale = 'de',
  maxItems = 5,
  className,
}: ActivityWidgetProps) {
  const t = useTranslations('widgets.activity');
  const dateLocale = locale === 'de' ? de : enUS;
  const [mounted, setMounted] = useState(false);

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

  const displayedActivities = activities.slice(0, maxItems);

  return (
    <WidgetContainer
      id={id}
      title={t('name')}
      icon={<Activity className="h-4 w-4 text-primary" />}
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
      colSpan={2}
    >
      <ScrollArea className="h-[280px] pr-4">
        {isLoading ? (
          <div className="space-y-4">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="flex gap-4">
                <Skeleton className="h-10 w-10 rounded-full" />
                <div className="flex-1 space-y-2">
                  <Skeleton className="h-4 w-3/4" />
                  <Skeleton className="h-3 w-1/2" />
                </div>
              </div>
            ))}
          </div>
        ) : displayedActivities.length === 0 ? (
          <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
            {t('noActivity')}
          </div>
        ) : (
          <div className="space-y-4">
            {displayedActivities.map((activity, index) => {
              const Icon = activity.icon || getActivityIcon(activity.type);
              const iconColor = activity.iconColor || getActivityColor(activity.type);

              return (
                <motion.div
                  key={activity.id}
                  initial={{ opacity: 0, x: -10 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ duration: 0.2, delay: index * 0.05 }}
                  className="flex gap-4"
                >
                  {/* Icon or Avatar */}
                  <div className="flex-shrink-0">
                    {activity.user ? (
                      <Avatar className="h-10 w-10">
                        <AvatarImage src={activity.user.image} />
                        <AvatarFallback className="text-xs">
                          {activity.user.name
                            .split(' ')
                            .map((n) => n[0])
                            .join('')
                            .toUpperCase()}
                        </AvatarFallback>
                      </Avatar>
                    ) : (
                      <div className={cn('flex h-10 w-10 items-center justify-center rounded-full bg-muted', iconColor)}>
                        <Icon className="h-5 w-5" />
                      </div>
                    )}
                  </div>

                  {/* Content */}
                  <div className="flex-1 space-y-1">
                    <p className="text-sm font-medium leading-none">{activity.title}</p>
                    {activity.description && (
                      <p className="text-sm text-muted-foreground">{activity.description}</p>
                    )}
                    <p className="text-xs text-muted-foreground">
                      {mounted
                        ? formatDistanceToNow(activity.timestamp, {
                            addSuffix: true,
                            locale: dateLocale,
                          })
                        : '\u00A0'}
                    </p>
                  </div>
                </motion.div>
              );
            })}
          </div>
        )}
      </ScrollArea>
    </WidgetContainer>
  );
}
