"use client";

import { useCallback, useEffect, useState } from "react";
import type { GitHubIssueLink, IntegrationConnection } from "@/types";

export function useTaskGitHubLinks(taskId: string, teamId: string | null) {
  const [connections, setConnections] = useState<IntegrationConnection[]>([]);
  const [links, setLinks] = useState<GitHubIssueLink[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchAll = useCallback(async () => {
    if (!taskId) {
      setConnections([]);
      setLinks([]);
      setLoading(false);
      return;
    }

    setLoading(true);
    const teamQuery = teamId ? `?teamId=${encodeURIComponent(teamId)}` : "";
    const [connectionsRes, linksRes] = await Promise.all([
      fetch(`/api/integrations/github${teamQuery}`),
      fetch(`/api/tasks/${taskId}/github-links`),
    ]);

    const connectionsJson = connectionsRes.ok ? await connectionsRes.json() : { connections: [] };
    const linksJson = linksRes.ok ? await linksRes.json() : { links: [] };

    setConnections(connectionsJson.connections || []);
    setLinks(linksJson.links || []);
    setLoading(false);
  }, [taskId, teamId]);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      void fetchAll();
    }, 0);

    return () => window.clearTimeout(timer);
  }, [fetchAll]);

  async function createIssue(input: { connectionId: string; body?: string }) {
    const res = await fetch(`/api/tasks/${taskId}/github-links`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(input),
    });

    const json = await res.json();
    if (!res.ok) {
      throw new Error(json.error || "GitHub issue could not be created");
    }

    setLinks((prev) => [json.link, ...prev]);
    return json.link as GitHubIssueLink;
  }

  async function deleteLink(linkId: string) {
    const res = await fetch(`/api/tasks/${taskId}/github-links/${linkId}`, {
      method: "DELETE",
    });

    const json = await res.json();
    if (!res.ok) {
      throw new Error(json.error || "GitHub issue link could not be deleted");
    }

    setLinks((prev) => prev.filter((link) => link.id !== linkId));
  }

  return {
    connections,
    links,
    loading,
    createIssue,
    deleteLink,
    refetch: fetchAll,
  };
}
