"use client";

import { useState } from "react";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import PortfolioTaskList from "./PortfolioTaskList";
import PortfolioSubtaskDetails from "./PortfolioSubtaskDetails";

export interface Task {
  id: string;
  taskSource: string;
  jobStarted: string | null;
  jobCompleted: string | null;
  status: string;
  service: string | null;
  updatedAt: string;
}

export interface PortfolioTask extends Task {
  totalSubtasks: number;
  completedSubtasks: number;
  failedSubtasks: number;
}

export interface SubTask {
  id: string;
  taskId: string;
  jobStarted: string | null;
  jobCompleted: string | null;
  status: string;
  inputs: string | null;
  outputs: string | null;
  cloudLogsURL: string | null;
  updatedAt: string;
}

interface TasksResponse {
  tasks: PortfolioTask[];
  total: number;
  limit: number;
  offset: number;
}

export default function PortfolioLogs({ portfolioId }: { portfolioId: string }) {
  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);

  const {
    data: tasksData,
    isLoading,
    isFetchingNextPage,
    isError,
    error: tasksError,
    fetchNextPage,
    refetch,
  } = useInfiniteQuery<TasksResponse>({
    queryKey: ["portfolioTasks", portfolioId],
    queryFn: async ({ pageParam = 0 }) => {
      const response = await fetch(
        `/api/portfolio/${portfolioId}/tasks?limit=20&offset=${pageParam}`
      );
      if (!response.ok) throw new Error("Failed to fetch tasks");
      return response.json();
    },
    getNextPageParam: (lastPage) => {
      const nextOffset = lastPage.offset + lastPage.tasks.length;
      return nextOffset < lastPage.total ? nextOffset : undefined;
    },
    enabled: !!portfolioId,
  });

  const tasks = tasksData?.pages.flatMap((p) => p.tasks) ?? [];
  const total = tasksData?.pages[0]?.total ?? 0;
  const errorMessage = isError
    ? (tasksError instanceof Error ? tasksError.message : "An error occurred")
    : null;

  const { data: subtasks = [] } = useQuery<SubTask[]>({
    queryKey: ["taskSubtasks", selectedTaskId],
    queryFn: async () => {
      const response = await fetch(`/api/tasks/${selectedTaskId}`);
      if (!response.ok) throw new Error("Failed to fetch subtasks");
      return response.json();
    },
    enabled: !!selectedTaskId,
  });

  const selectedTask = tasks.find((t) => t.id === selectedTaskId);

  return (
    <div className="flex min-h-[600px] max-h-[calc(100vh-220px)] border border-gray-200 rounded-lg overflow-hidden bg-gray-50">
      {/* Left sidebar - Task list */}
      <div className="w-80 border-r border-gray-200 bg-white shrink-0">
        <PortfolioTaskList
          tasks={tasks}
          selectedTaskId={selectedTaskId}
          onSelectTask={setSelectedTaskId}
          loading={isLoading}
          loadingMore={isFetchingNextPage}
          error={errorMessage}
          total={total}
          onLoadMore={() => fetchNextPage()}
          onRefresh={() => refetch()}
        />
      </div>

      {/* Right side - Subtask details */}
      <div className="flex-1 overflow-auto">
        {selectedTaskId ? (
          <PortfolioSubtaskDetails
            subtasks={subtasks}
            task={selectedTask}
          />
        ) : (
          <div className="flex items-center justify-center h-full text-gray-500 text-sm">
            Select a task to view its subtasks
          </div>
        )}
      </div>
    </div>
  );
}
