"use client";

import { useCallback, useState } from "react";
import { useQueryState } from "nuqs";
import { usePathname } from "next/navigation";
import { Loader, Plus, Table, Kanban, Calendar, ChevronDown, Target, CheckSquare, Group } from "lucide-react";

import { DottedSeparator } from "@/components/dotted-separator";
import { useWorkspaceId } from "@/features/workspaces/hooks/use-workspace-id";
import { useProjectId } from "@/features/projects/hooks/use-project-id";
import { useGetCurrentMember } from "@/features/members/api/use-get-current-member";

import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

import { columns } from "./columns";
import { DataTable } from "./data-table";
import { DataTableEpicGrouped } from "./data-table-epic-grouped";
import { DataKanban } from "./data-kanban";
import { DataKanbanGrouped } from "./data-kanban-grouped";
import { DataFilters } from "./data-filters";
import { DataCalendar } from "./data-calendar";

import { TaskStatus } from "../types";
import { useGetTasks } from "../api/use-get-tasks";
import { useTaskFilters } from "../hooks/use-task-filters";
import { useCreateTaskModal } from "../hooks/use-create-task-modal";
import { useCreateEpicModal } from "@/features/epics/hooks/use-create-epic-modal";
import { useBulkUpdateTasks } from "../api/use-bulk-update-tasks";

interface TaskViewSwitcherProps {
  hideProjectFilter?: boolean;
  boardId?: string;
}

export const TaskViewSwitcher = ({
  hideProjectFilter,
  boardId,
}: TaskViewSwitcherProps) => {
  const pathname = usePathname();
  const [{ status, assigneeId, projectId, dueDate, search, labels, groupBy, labelsOperator }] = useTaskFilters();
  const [epicGrouping, setEpicGrouping] = useState(false);

  const [view, setView] = useQueryState("task-view", {
    defaultValue: "table",
  });

  const workspaceId = useWorkspaceId();
  const paramProjectId = useProjectId();
  const { open: openTaskModal } = useCreateTaskModal();
  const { open: openEpicModal } = useCreateEpicModal();
  const { mutate: bulkUpdate } = useBulkUpdateTasks();
  const { data: currentMember } = useGetCurrentMember({ workspaceId });

  // Check if we're on the workspace tasks page (should show only current user's tasks)
  const isWorkspaceTasksPage = pathname.includes('/tasks') && !pathname.includes('/projects/');
  
  // Auto-set assigneeId to current user's member ID on workspace tasks page
  const effectiveAssigneeId = isWorkspaceTasksPage && currentMember && !assigneeId 
    ? currentMember.id 
    : assigneeId;

  const { data: tasks, isLoading: isLoadingTasks } = useGetTasks({
    workspaceId,
    projectId: paramProjectId || projectId,
    assigneeId: effectiveAssigneeId,
    status,
    dueDate,
    search,
    boardId,
    labels,
  });

  const onKanbanChange = useCallback(
    (
      tasks: {
        $id: string;
        status: TaskStatus;
        position: number;
      }[]
    ) => {
      bulkUpdate({
        json: { tasks },
      });
    }, [bulkUpdate]);

  const isGrouped = groupBy && groupBy !== "none";
  const hideGroupByFilter = groupBy === "none";
  
  // Hide board tab on workspace tasks page (e.g., /workspaces/[id]/tasks)
  // Show board tab only for project boards or when boardId is provided
  const showBoardTab = !isWorkspaceTasksPage || !!boardId;

  return (
    <Tabs
      defaultValue={view}
      onValueChange={setView}
      className="flex-1 w-full border rounded-lg"
    >
      <div className="h-full flex flex-col overflow-auto p-4">
        <div className="flex flex-col lg:flex-row gap-y-2 items-center justify-between w-full">
          <TabsList className="w-full lg:w-auto bg-white/50 backdrop-blur-sm border-none shadow-sm">
            <TabsTrigger className="h-9 w-full lg:w-auto 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" value="table">
              <Table className="h-4 w-4" />
              <span className="hidden sm:inline">Table</span>
            </TabsTrigger>
            {showBoardTab && (
              <TabsTrigger className="h-9 w-full lg:w-auto 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" value="kanban">
                <Kanban className="h-4 w-4" />
                <span className="hidden sm:inline">Kanban</span>
              </TabsTrigger>
            )}
            <TabsTrigger className="h-9 w-full lg:w-auto 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" value="calendar">
              <Calendar className="h-4 w-4" />
              <span className="hidden sm:inline">Calendar</span>
            </TabsTrigger>
          </TabsList>
          
          <div className="flex items-center gap-2">
            {/* Epic Grouping Toggle */}
            {view === "table" && (
              <Button
                variant={epicGrouping ? "secondary" : "outline"}
                size="sm"
                onClick={() => setEpicGrouping(!epicGrouping)}
                className="flex items-center gap-2"
              >
                <Group className="h-4 w-4" />
                <span className="hidden sm:inline">
                  {epicGrouping ? "Grouped by Epic" : "Group by Epic"}
                </span>
                <span className="sm:hidden">Epic</span>
              </Button>
            )}

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button size="sm" className="w-full lg:w-auto">
                  <Plus className="size-4 mr-2" />
                  New
                  <ChevronDown className="size-4 ml-2" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => openTaskModal()}>
                  <CheckSquare className="size-4 mr-2" />
                  New Task
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => openEpicModal()}>
                  <Target className="size-4 mr-2" />
                  New Epic
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
        <DottedSeparator className="my-4" />
        <DataFilters 
          hideProjectFilter={hideProjectFilter} 
          hideGroupByFilter={isWorkspaceTasksPage}
          hideAssigneeFilter={isWorkspaceTasksPage} 
        />
        <DottedSeparator className="my-4" />
        {isLoadingTasks ? (
          <div className="w-full border rounded-lg h-[200px] flex flex-col items-center justify-center">
            <Loader className="size-5 animate-spin text-muted-foreground" />
          </div>
        ) : (
          <>
            <TabsContent value="table" className="mt-0">
              {epicGrouping ? (
                <DataTableEpicGrouped columns={columns} data={tasks?.documents ?? [] as any} />
              ) : (
                /* @ts-ignore */
                <DataTable columns={columns} data={tasks?.documents ?? []} />
              )}
            </TabsContent>
            {showBoardTab && (
              <TabsContent value="kanban" className="mt-0">
                {isGrouped ? (
                  <DataKanbanGrouped 
                    onChange={onKanbanChange} 
                    data={tasks?.documents ?? [] as any} 
                    groupBy={groupBy as any}
                  />
                ) : (
                  <DataKanban onChange={onKanbanChange} data={tasks?.documents ?? [] as any} />
                )}
              </TabsContent>  
            )}
            <TabsContent value="calendar" className="mt-0 h-full pb-4">
              {/* @ts-ignore */}
              <DataCalendar data={tasks?.documents ?? [] as any} />
            </TabsContent>
          </>
        )}
      </div>
    </Tabs>
  );
};
