"use client"

import { useState, useEffect } from "react"
import {
  FolderPlus,
  Edit,
  Trash2,
  ArrowRight,
  MessageSquare,
  Upload,
  CheckSquare,
  Activity,
} from "lucide-react"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { LoadingSpinner } from "@/components/ui/loading-spinner"
import { subscribeToActivityLogs, getRecentActivityLogs } from "@/lib/firebase/index"
import type { ActivityLog, ActivityAction } from "@/lib/types"
import { getInitials, getRelativeTime } from "@/lib/utils"

interface ActivityFeedProps {
  projectId?: string
  limit?: number
}

const actionIcons: Record<ActivityAction, typeof Activity> = {
  project_created: FolderPlus,
  project_updated: Edit,
  project_deleted: Trash2,
  task_created: FolderPlus,
  task_updated: Edit,
  task_deleted: Trash2,
  task_moved: ArrowRight,
  comment_added: MessageSquare,
  file_uploaded: Upload,
  subtask_added: CheckSquare,
  subtask_completed: CheckSquare,
}

const actionColors: Record<ActivityAction, string> = {
  project_created: "bg-emerald-500/10 text-emerald-600",
  project_updated: "bg-blue-500/10 text-blue-600",
  project_deleted: "bg-red-500/10 text-red-600",
  task_created: "bg-emerald-500/10 text-emerald-600",
  task_updated: "bg-blue-500/10 text-blue-600",
  task_deleted: "bg-red-500/10 text-red-600",
  task_moved: "bg-amber-500/10 text-amber-600",
  comment_added: "bg-purple-500/10 text-purple-600",
  file_uploaded: "bg-cyan-500/10 text-cyan-600",
  subtask_added: "bg-indigo-500/10 text-indigo-600",
  subtask_completed: "bg-emerald-500/10 text-emerald-600",
}

export function ActivityFeed({ projectId, limit = 20 }: ActivityFeedProps) {
  const [activities, setActivities] = useState<ActivityLog[]>([])
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    if (projectId) {
      // Subscribe to project-specific activities
      try {
        const unsubscribe = subscribeToActivityLogs(
          projectId,
          (logs) => {
            setActivities(logs)
            setIsLoading(false)
          },
          limit
        )
        return () => unsubscribe()
      } catch (error) {
        console.error('Failed to subscribe to activity logs:', error)
        setIsLoading(false)
      }
    } else {
      // Fetch recent activities (no real-time subscription for all)
      getRecentActivityLogs(limit)
        .then((logs) => {
          setActivities(logs)
          setIsLoading(false)
        })
        .catch((error) => {
          console.error('Failed to fetch activity logs:', error)
          setIsLoading(false)
        })
    }
  }, [projectId, limit])

  if (isLoading) {
    return (
      <div className="flex justify-center py-8">
        <LoadingSpinner />
      </div>
    )
  }

  if (activities.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-8 text-center">
        <Activity className="h-8 w-8 text-muted-foreground mb-2" />
        <p className="text-sm text-muted-foreground">No activity yet</p>
      </div>
    )
  }

  return (
    <ScrollArea className="h-[400px]">
      <div className="space-y-4 pr-4">
        {activities.map((activity, index) => {
          const Icon = actionIcons[activity.action] || Activity
          const colorClass = actionColors[activity.action] || "bg-muted"

          return (
            <div
              key={activity.id}
              className="flex gap-3 animate-fade-in"
              style={{ animationDelay: `${index * 30}ms` }}
            >
              {/* Icon */}
              <div
                className={`h-8 w-8 rounded-full flex items-center justify-center flex-shrink-0 ${colorClass}`}
              >
                <Icon className="h-4 w-4" />
              </div>

              {/* Content */}
              <div className="flex-1 min-w-0 pt-0.5">
                <p className="text-sm">
                  <span className="font-medium">{activity.actorName}</span>{" "}
                  <span className="text-muted-foreground">
                    {activity.description.replace(activity.actorName, "").trim()}
                  </span>
                </p>
                <p className="text-xs text-muted-foreground mt-0.5">
                  {getRelativeTime(activity.createdAt)}
                </p>
              </div>
            </div>
          )
        })}
      </div>
    </ScrollArea>
  )
}

