"use client";

import { TrendingUp, Layout, Cog } from "lucide-react";

import { useGetProject } from "@/features/projects/api/use-get-project";
import { useProjectId } from "@/features/projects/hooks/use-project-id";
import { ProjectAvatar } from "@/features/projects/components/project-avatar";
import { TaskViewSwitcher } from "@/features/tasks/components/task-view-switcher";
import { useGetProjectAnalytics } from "@/features/projects/api/use-get-project-analytics";
import { BoardsList } from "@/features/boards/components/boards-list";
import { useGetTasks } from "@/features/tasks/api/use-get-tasks";
import { useGetEpics } from "@/features/epics/api/use-get-epics";
import { useGetMembers } from "@/features/members/api/use-get-members";
import { EditProjectForm } from "@/features/projects/components/edit-project-form";

import { Button } from "@/components/ui/button";
import { Analytics } from "@/components/analytics";
import { PageError } from "@/components/page-error";
import { PageLoader } from "@/components/page-loader";
import { Separator } from "@/components/ui/separator";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { 
  StatusOverview, 
  RecentActivity, 
  PriorityBreakdown, 
  TypesOfWork, 
  TeamWorkload 
} from "@/components/dashboard-widgets";
import { EpicStats } from "@/components/workspace-stats";
import { AnalyticsRow } from "@/components/analytics-cards";
import { formatDistanceToNow } from "date-fns";
import { useRouter } from "next/navigation";

export const ProjectIdClient = () => {
  const router = useRouter();
  const projectId = useProjectId();
  const { data: project, isLoading: isLoadingProject } = useGetProject({ projectId });
  const { data: analytics, isLoading: isLoadingAnalytics } = useGetProjectAnalytics({ projectId });
  
  const { data: tasks, isLoading: isLoadingTasks } = useGetTasks({
    workspaceId: project?.workspaceId || "",
    projectId,
  });

  const { data: epics, isLoading: isLoadingEpics } = useGetEpics({
    workspaceId: project?.workspaceId || "",
    projectId,
  });

  const { data: members, isLoading: isLoadingMembers } = useGetMembers({
    workspaceId: project?.workspaceId || "",
  });

  const isLoading = isLoadingProject || isLoadingAnalytics || isLoadingTasks || isLoadingEpics || isLoadingMembers;

  if (isLoading) {
    return <PageLoader />
  }

  if (!project) {
    return <PageError message="Project not found" />
  }

  const href = `/workspaces/${project.workspaceId}/projects/${project.id}/settings`;

  // Generate realistic recent activity data
  const recentActivity = tasks?.documents?.slice(0, 8).map((task: any, index: number) => {
    const activityTypes = ["created", "updated", "status_change", "assigned"] as const;
    const actions = {
      created: "created task",
      updated: "updated task", 
      status_change: "changed status of",
      assigned: "was assigned to"
    };
    
    const activityType = activityTypes[index % activityTypes.length];
    const user = task.assignee?.name || task.assignee?.email || "Unknown User";
    
    return {
      id: `${task.id}-${index}`,
      user,
      action: actions[activityType],
      target: task.name,
      time: formatDistanceToNow(new Date(task.updatedAt || task.createdAt), { addSuffix: true }),
      status: task.status,
      taskId: task.id,
      workspaceId: project.workspaceId,
      type: activityType
    };
  }) || [];

  const handleActivityClick = (activity: any) => {
    if (activity.taskId) {
      router.push(`/workspaces/${activity.workspaceId}/tasks/${activity.taskId}`);
    }
  };

  // Calculate dynamic status overview based on actual TaskStatus enum
  const statusOverview = {
    backlog: tasks?.documents?.filter((task: any) => task.status === "BACKLOG").length || 0,
    todo: tasks?.documents?.filter((task: any) => task.status === "TODO").length || 0,
    inProgress: tasks?.documents?.filter((task: any) => task.status === "IN_PROGRESS").length || 0,
    inReview: tasks?.documents?.filter((task: any) => task.status === "IN_REVIEW").length || 0,
    done: tasks?.documents?.filter((task: any) => task.status === "DONE").length || 0,
  };

  const priorityBreakdown = {
    highest: Math.floor((tasks?.total || 0) * 0.1),
    high: Math.floor((tasks?.total || 0) * 0.2),
    medium: Math.floor((tasks?.total || 0) * 0.4),
    low: Math.floor((tasks?.total || 0) * 0.2),
    lowest: Math.floor((tasks?.total || 0) * 0.1),
  };

  const typesOfWork = {
    task: Math.floor((tasks?.total || 0) * 0.7),
    epic: Math.floor((tasks?.total || 0) * 0.2),
    subtask: Math.floor((tasks?.total || 0) * 0.1),
  };

  return (
    <div className="flex flex-col">
      <Tabs defaultValue="summary" className="w-full">
        <TabsList className="grid w-full grid-cols-3 bg-white/50 backdrop-blur-sm border-none shadow-sm">
          <TabsTrigger value="summary" className="flex items-center gap-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-gray-50 data-[state=active]:to-slate-50 data-[state=active]:text-gray-700 data-[state=active]:border-gray-200">
            <TrendingUp className="h-4 w-4" />
            <span className="hidden sm:inline">Overview</span>
            <span className="sm:hidden">Stats</span>
          </TabsTrigger>
          <TabsTrigger value="boards" className="flex items-center gap-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-gray-50 data-[state=active]:to-slate-50 data-[state=active]:text-gray-700 data-[state=active]:border-gray-200">
            <Layout className="h-4 w-4" />
            <span className="hidden sm:inline">Boards</span>
            <span className="sm:hidden">Boards</span>
          </TabsTrigger>
          <TabsTrigger value="settings" className="flex items-center gap-2 data-[state=active]:bg-gradient-to-r data-[state=active]:from-gray-50 data-[state=active]:to-slate-50 data-[state=active]:text-gray-700 data-[state=active]:border-gray-200">
            <Cog className="h-4 w-4" />
            <span className="hidden sm:inline">Settings</span>
            <span className="sm:hidden">Config</span>
          </TabsTrigger>
        </TabsList>

        <TabsContent value="summary" className="mt-6">
          <div className="space-y-6">
            {analytics && <AnalyticsRow data={analytics as any} />}
            
            <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
              <StatusOverview data={statusOverview} />
              {epics && epics.length > 0 && (
                <EpicStats epics={epics as any} />
              )}
              <div className="lg:col-span-2">
                <RecentActivity 
                  activities={recentActivity} 
                  onActivityClick={handleActivityClick}
                />
              </div>
              
              {members && tasks && (
                <div className="lg:col-span-4">
                  <TeamWorkload 
                    members={members.documents || []} 
                    tasks={(tasks.documents as any) || []} 
                  />
                </div>
              )}
            </div>
          </div>
        </TabsContent>

        <TabsContent value="boards" className="mt-6">
          <div className="space-y-4">
            <BoardsList />
            
            <Separator />
            
            {/* <div className="space-y-4">
              <h2 className="text-2xl font-bold">All Tasks</h2>
              <TaskViewSwitcher hideProjectFilter />
            </div> */}
          </div> 
        </TabsContent>

        <TabsContent value="settings" className="mt-6">
          <EditProjectForm initialValues={project as any} />
        </TabsContent>
      </Tabs>
    </div>
  )
}
