"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { Task } from "@/features/tasks/types";
import { formatDistanceToNow } from "date-fns";
import { CalendarIcon, PlusIcon, SettingsIcon, BarChart3, Users, Settings, FolderKanban, Building2, UserCheck, Cog, ShieldAlert, Target } from "lucide-react";

import { Member } from "@/features/members/types";
import { Project } from "@/features/projects/types";
import { useGetTasks } from "@/features/tasks/api/use-get-tasks";
import { useGetMembers } from "@/features/members/api/use-get-members";
import { useGetProjects } from "@/features/projects/api/use-get-projects";
import { useGetEpics } from "@/features/epics/api/use-get-epics";
import { useGetWorkspace } from "@/features/workspaces/api/use-get-workspace";
import { useGetCurrentMember } from "@/features/members/api/use-get-current-member";
import { MemberAvatar } from "@/features/members/components/member-avatar";
import { ProjectAvatar } from "@/features/projects/components/project-avatar";
import { useWorkspaceId } from "@/features/workspaces/hooks/use-workspace-id";

import { useGetWorkspaceAnalytics } from "@/features/workspaces/api/use-get-workspace-analytics";
import { EditWorkspaceForm } from "@/features/workspaces/components/edit-workspace-form";
import { MemberRole } from "@/features/members/types";

import { Button } from "@/components/ui/button";
import { Analytics } from "@/components/analytics";
import { PageError } from "@/components/page-error";
import { Card, CardContent } from "@/components/ui/card";
import { PageLoader } from "@/components/page-loader";
import { DottedSeparator } from "@/components/dotted-separator";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  StatusOverview,
  RecentActivity,
  TeamWorkload
} from "@/components/dashboard-widgets";
import {
  WorkspaceProjectStats,
  WorkspaceDueDateStats,
  WorkspaceCommunicationStats,
  EpicStats
} from "@/components/workspace-stats";
import { AnalyticsRow } from "@/components/analytics-cards";
import { useCreateProjectModal } from "@/features/projects/hooks/use-create-project-modal";
import { useCreateEpicModal } from "@/features/epics/hooks/use-create-epic-modal";
import { useEditEpicModal } from "@/features/epics/hooks/use-edit-epic-modal";

export const WorkspaceIdClient = () => {
  const router = useRouter();
  const workspaceId = useWorkspaceId();

  const { data: analytics, isLoading: isLoadingAnalytics } = useGetWorkspaceAnalytics({ workspaceId });
  const { data: tasks, isLoading: isLoadingTasks } = useGetTasks({ workspaceId });
  const { data: projects, isLoading: isLoadingProjects } = useGetProjects({ workspaceId });
  const { data: epics, isLoading: isLoadingEpics } = useGetEpics({ workspaceId });
  const { data: members, isLoading: isLoadingMembers } = useGetMembers({ workspaceId });
  const { data: workspace, isLoading: isLoadingWorkspace } = useGetWorkspace({ workspaceId });
  const { data: currentMember, isLoading: isLoadingCurrentMember } = useGetCurrentMember({ workspaceId });

  const isLoading = isLoadingAnalytics || isLoadingTasks || isLoadingProjects || isLoadingEpics || isLoadingMembers || isLoadingWorkspace || isLoadingCurrentMember;

  if (isLoading) {
    return <PageLoader />;
  }

  if (!analytics || !tasks || !projects || !epics || !members || !workspace || !currentMember) {
    return <PageError message="Failed to load workspace data" />;
  }

  const isCurrentUserAdmin = currentMember.role === MemberRole.ADMIN;

  // 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: 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,
    todo: tasks.documents.filter((task: any) => task.status === "TODO").length,
    inProgress: tasks.documents.filter((task: any) => task.status === "IN_PROGRESS").length,
    inReview: tasks.documents.filter((task: any) => task.status === "IN_REVIEW").length,
    done: tasks.documents.filter((task: any) => task.status === "DONE").length,
  };

  return (
    <div className="h-full flex flex-col">
      <Tabs defaultValue="summary" className="w-full">
        <TabsList className="grid w-full grid-cols-4 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">
            <BarChart3 className="h-4 w-4" />
            <span className="hidden md:inline">Dashboard</span>
            <span className="md:hidden">Stats</span>
          </TabsTrigger>
          <TabsTrigger value="projects" 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">
            <FolderKanban className="h-4 w-4" />
            <span className="hidden md:inline">Projects</span>
            <span className="md:hidden">Work</span>
          </TabsTrigger>
          <TabsTrigger value="members" 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">
            <UserCheck className="h-4 w-4" />
            <span className="hidden md:inline">Team</span>
            <span className="md:hidden">Team</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 md:inline">Settings</span>
            <span className="md:hidden">Config</span>
          </TabsTrigger>
        </TabsList>

        <TabsContent value="summary" className="mt-6">
          <div className="space-y-6">
            <AnalyticsRow data={analytics} />

            <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
              <StatusOverview data={statusOverview} />
              <EpicStats epics={epics || []} />
              <WorkspaceDueDateStats tasks={tasks.documents} />
              <WorkspaceCommunicationStats analytics={analytics} />

              <div className="lg:col-span-2">
                <RecentActivity
                  activities={recentActivity}
                  onActivityClick={handleActivityClick}
                />
              </div>
              <div className="lg:col-span-2">
                <TeamWorkload members={members.documents} tasks={tasks.documents as unknown as Task[]} />
              </div>

              <div className="lg:col-span-4">
                <WorkspaceProjectStats
                  tasks={tasks.documents}
                  projects={projects.documents}
                  members={members.documents}
                />
              </div>
            </div>
          </div>
        </TabsContent>

        <TabsContent value="projects" className="mt-6">
          <div className="space-y-4">
            <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">
              <TaskList data={tasks.documents as any} total={tasks.total} />
              <EpicList data={epics || []} total={epics?.length || 0} />
              <ProjectList data={projects.documents as any} total={projects.total} />
            </div>
          </div>
        </TabsContent>

        <TabsContent value="members" className="mt-6">
          <div className="space-y-4">
            <MembersList data={members.documents} total={members.total} isAdmin={isCurrentUserAdmin} />
          </div>
        </TabsContent>

        <TabsContent value="settings" className="mt-6">
          {isCurrentUserAdmin ? (
            <EditWorkspaceForm initialValues={workspace} />
          ) : (
            <div className="space-y-4">
              <div className="text-center py-12">
                <ShieldAlert className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                <h3 className="text-lg font-medium mb-2">Access Restricted</h3>
                <p className="text-muted-foreground mb-4">
                  You don't have permission to access workspace settings. Only administrators can modify workspace settings.
                </p>
              </div>
            </div>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
};

interface TaskListProps {
  data: Task[];
  total: number;
}

export const TaskList = ({ data, total }: TaskListProps) => {
  const workspaceId = useWorkspaceId();

  return (
    <div className="flex flex-col gap-y-4 col-span-1">
      <div className="bg-muted rounded-lg p-4">
        <div className="flex items-center justify-between">
          <p className="text-lg font-semibold">Tasks ({total})</p>
          <Button variant="muted" size="icon" asChild>
            <Link href={`/workspaces/${workspaceId}/tasks`}>
              <PlusIcon className="size-4 text-neutral-400" />
            </Link>
          </Button>
        </div>
        <DottedSeparator className="my-4" />
        <ul className="flex flex-col gap-y-4">
          {data.map((task) => (
            <li key={task.id}>
              <Link href={`/workspaces/${workspaceId}/tasks/${task.id}`}>
                <Card className="shadow-none rounded-lg hover:opacity-75 transition">
                  <CardContent className="p-4">
                    <p className="text-lg font-medium truncate">{task.name}</p>
                    <div className="flex items-center gap-x-2">
                      <p>{task.project?.name}</p>
                      <div className="dot" />
                      <div className="text-sm text-muted-foreground flex items-center">
                        <CalendarIcon className="size-3 mr-1" />
                        <span className="truncate">
                          {task.dueDate ? formatDistanceToNow(new Date(task.dueDate)) : "No due date"}
                        </span>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </Link>
            </li>
          ))}
          <li className="text-sm text-muted-foreground text-center hidden first-of-type:block">
            No tasks found
          </li>
        </ul>
        <Button variant="muted" className="mt-4 w-full" asChild>
          <Link href={`/workspaces/${workspaceId}/tasks`}>Show All</Link>
        </Button>
      </div>
    </div>
  );
};

interface EpicListProps {
  data: any[];
  total: number;
}

export const EpicList = ({ data, total }: EpicListProps) => {
  const workspaceId = useWorkspaceId();
  const { open } = useCreateEpicModal();
  const { open: editOpen } = useEditEpicModal();

  const handleEpicClick = (epicId: string) => {
    editOpen(epicId);
  };

  return (
    <div className="flex flex-col gap-y-4 col-span-1">
      <div className="bg-gradient-to-br from-purple-50 to-blue-50 border border-purple-200 rounded-lg p-4">
        <div className="flex items-center justify-between">
          <p className="text-lg font-semibold">Epics ({total})</p>
          
          <Button variant="outline" size="icon" onClick={open}>
              <PlusIcon className="size-4 text-neutral-400" />
          </Button>
        </div>
        <DottedSeparator className="my-4" />
        <ul className="flex flex-col gap-y-4">
          {data.map((epic) => (
            <li key={epic.id}>
              <Card 
                className="shadow-none rounded-lg hover:opacity-75 transition cursor-pointer"
                onClick={() => handleEpicClick(epic.id)}
              >
                <CardContent className="p-4">
                  <div className="flex items-center gap-x-2 mb-2">
                    <Target className="size-4 text-purple-600" />
                    <p className="text-lg font-medium truncate">{epic.name}</p>
                  </div>
                  <div className="flex items-center gap-x-2">
                    <p className="text-sm text-muted-foreground">{epic.project?.name}</p>
                    {epic.stats && (
                      <>
                        <div className="dot" />
                        <div className="text-sm text-muted-foreground">
                          {epic.stats.completedTasks}/{epic.stats.totalTasks} tasks
                        </div>
                      </>
                    )}
                  </div>
                </CardContent>
              </Card>
            </li>
          ))}
          <li className="text-sm text-muted-foreground text-center hidden first-of-type:block">
            No epics found
          </li>
        </ul>
      </div>
    </div>
  );
};

interface ProjectListProps {
  data: Project[];
  total: number;
}
export const ProjectList = ({ data, total }: ProjectListProps) => {
  const workspaceId = useWorkspaceId();
  const { open } = useCreateProjectModal();

  return (
    <div className="flex flex-col gap-y-4 col-span-1">
      <div className="bg-white border rounded-lg p-4">
        <div className="flex items-center justify-between">
          <p className="text-lg font-semibold">Projects ({total})</p>
          
          <Button variant="outline" size="icon" onClick={open}>
              <PlusIcon className="size-4 text-neutral-400" />
          </Button>
        </div>
        <DottedSeparator className="my-4" />
        <ul className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          {data.map((project) => (
            <li key={project.id}>
              <Link href={`/workspaces/${workspaceId}/projects/${project.id}`}>
                <Card className="shadow-none rounded-lg hover:opacity-75 transition">
                  <CardContent className="p-4 flex items-center gap-x-2.5">
                    <ProjectAvatar
                      className="size-12"
                      fallbackClassName="text-lg"
                      name={project.name}
                      image={project.imageUrl}
                    />
                    <p className="text-lg font-medium truncate">
                      {project.name}
                    </p>
                  </CardContent>
                </Card>
              </Link>
            </li>
          ))}
          <li className="text-sm text-muted-foreground text-center hidden first-of-type:block">
            No projects found
          </li>
        </ul>
      </div>
    </div>
  );
};

interface MembersListProps {
  data: Member[];
  total: number;
  isAdmin: boolean;
}
export const MembersList = ({ data, total, isAdmin }: MembersListProps) => {
  const workspaceId = useWorkspaceId();

  return (
    <div className="flex flex-col gap-y-4 col-span-1">
      <div className="bg-white border rounded-lg p-4">
        <div className="flex items-center justify-between">
          <p className="text-lg font-semibold">Members ({total})</p>
          {isAdmin && (
            <Button asChild variant="tertiary" size="icon">
              <Link href={`/workspaces/${workspaceId}/members`}>
                <SettingsIcon className="size-4 text-neutral-400" />
              </Link>
            </Button>
          )}
        </div>
        <DottedSeparator className="my-4" />
        <ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {data.map((member) => (
            <li key={member.id}>
              <Card className="shadow-none rounded-lg overflow-hidden">
                <CardContent className="p-3 flex flex-col items-center gap-x-2">
                  <MemberAvatar className="size-12" name={member.name || member.email} />
                  <div className="flex flex-col items-center overflow-hidden">
                    <p className="text-lg font-medium line-clamp-1">
                      {member.name}
                    </p>
                    <p className="text-sm text-muted-foreground line-clamp-1">
                      {member.email}
                    </p>
                  </div>
                </CardContent>
              </Card>
            </li>
          ))}
          <li className="text-sm text-muted-foreground text-center hidden first-of-type:block">
            No members found
          </li>
        </ul>
      </div>
    </div>
  );
};