"use client";

import { useEffect, useState } from "react";
import { AlertCircle, GitBranch } from "lucide-react";

import {
  getBoardForgejoRepositories,
  getForgejoIssues,
  type ForgejoIssue,
  type ForgejoRepository,
} from "@/lib/api-forgejo";
import { ForgejoIssuesTable } from "@/components/git/ForgejoIssuesTable";

interface BoardForgejoIssuesPanelProps {
  boardId: string;
  canClose?: boolean;
  repositories?: ForgejoRepository[];
}

export function BoardForgejoIssuesPanel({
  boardId,
  canClose = false,
  repositories = [],
}: BoardForgejoIssuesPanelProps) {
  const [issues, setIssues] = useState<ForgejoIssue[]>([]);
  const [hasLinkedRepos, setHasLinkedRepos] = useState<boolean | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!boardId) return;
    let cancelled = false;

    const load = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const [linksResult, issuesResult] = await Promise.all([
          getBoardForgejoRepositories(boardId),
          getForgejoIssues({ board_id: boardId, state: "open", limit: 50 }),
        ]);
        if (cancelled) return;
        const links = Array.isArray(linksResult)
          ? linksResult
          : (linksResult.repositories ?? []);
        setHasLinkedRepos(links.length > 0);
        setIssues(issuesResult.items);
      } catch (err) {
        if (cancelled) return;
        setError(
          err instanceof Error
            ? err.message
            : "Could not load Git Project issues.",
        );
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    };

    load();
    return () => {
      cancelled = true;
    };
  }, [boardId]);

  const handleRefresh = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const issuesResult = await getForgejoIssues({
        board_id: boardId,
        state: "open",
        limit: 50,
      });
      setIssues(issuesResult.items);
    } catch (err) {
      setError(
        err instanceof Error
          ? err.message
          : "Could not refresh Git Project issues.",
      );
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <section className="rounded-xl border border-[color:var(--border)] bg-[color:var(--surface)] p-4 shadow-lush sm:p-5">
      <div className="mb-4 flex items-start justify-between gap-3">
        <div className="min-w-0">
          <h3 className="text-sm font-semibold text-strong">
            Git Project Issues
          </h3>
          <p className="mt-1 text-sm text-muted">
            Open issues from repositories linked to this board.
          </p>
        </div>
        {!isLoading && issues.length > 0 && (
          <span className="shrink-0 rounded-full border border-[color:var(--accent)]/30 bg-[color:var(--accent-soft)] px-2 py-0.5 text-xs font-medium text-[color:var(--accent)]">
            {issues.length} open
          </span>
        )}
      </div>

      {error ? (
        <div className="flex items-start gap-2 rounded-lg border border-[color:var(--danger)]/35 bg-[color:rgba(248,113,113,0.08)] px-3 py-2 text-sm text-[color:var(--danger)]">
          <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
          <span>{error}</span>
        </div>
      ) : hasLinkedRepos === false && !isLoading ? (
        <div className="rounded-lg border border-dashed border-[color:var(--border)] bg-[color:var(--surface-muted)] px-4 py-6 text-center">
          <div className="mx-auto mb-3 flex h-10 w-10 items-center justify-center rounded-full border border-[color:var(--border)] bg-[color:var(--surface)] text-muted">
            <GitBranch className="h-5 w-5" />
          </div>
          <p className="text-sm font-medium text-strong">
            No repositories linked
          </p>
          <p className="mt-1 text-sm text-muted">
            Link a Git Project repository to this board to see its open issues
            here.
          </p>
        </div>
      ) : (
        <ForgejoIssuesTable
          issues={issues}
          repositories={repositories}
          isLoading={isLoading}
          canClose={canClose}
          onRefresh={handleRefresh}
        />
      )}
    </section>
  );
}
