"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { AlertCircle, CheckCircle2 } from "lucide-react";

import { Button } from "@/components/ui/button";
import { useAuth } from "@/auth/clerk";
import { DashboardPageLayout } from "@/components/templates/DashboardPageLayout";
import { ForgejoRepositoriesTable } from "@/components/git/ForgejoRepositoriesTable";
import { ConfirmActionDialog } from "@/components/ui/confirm-action-dialog";
import {
  getForgejoRepositories,
  deleteForgejoRepository,
  syncRepository,
  validateRepository,
  type ForgejoRepository,
} from "@/lib/api-forgejo";

export default function ForgejoRepositoriesPage() {
  const router = useRouter();
  const auth = useAuth();

  const [repositories, setRepositories] = useState<ForgejoRepository[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<{
    tone: "success" | "error";
    message: string;
  } | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<ForgejoRepository | null>(
    null,
  );
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  useEffect(() => {
    const fetchRepositories = async () => {
      try {
        setIsLoading(true);
        const data = await getForgejoRepositories();
        setRepositories(data);
        setError(null);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load repositories",
        );
      } finally {
        setIsLoading(false);
      }
    };

    if (auth.isSignedIn) {
      fetchRepositories();
    }
  }, [auth.isSignedIn]);

  const repositoryName = (repository: ForgejoRepository) =>
    repository.display_name || `${repository.owner}/${repository.repo}`;

  const handleDelete = (repository: ForgejoRepository) => {
    setDeleteError(null);
    setDeleteTarget(repository);
  };

  const confirmDelete = async () => {
    if (!deleteTarget) return;
    setIsDeleting(true);
    setDeleteError(null);
    try {
      await deleteForgejoRepository(deleteTarget.id);
      setRepositories((prev) => prev.filter((r) => r.id !== deleteTarget.id));
      setNotice({
        tone: "success",
        message: `Deleted "${repositoryName(deleteTarget)}".`,
      });
      setDeleteTarget(null);
    } catch (err) {
      setDeleteError(
        err instanceof Error ? err.message : "Failed to delete repository",
      );
    } finally {
      setIsDeleting(false);
    }
  };

  const handleSync = async (repository: ForgejoRepository) => {
    try {
      const result = await syncRepository(repository.id);
      setNotice({
        tone: "success",
        message: `${repositoryName(repository)} synced: ${result.created} created, ${result.updated} updated, ${result.open} open, ${result.closed} closed.`,
      });
      // Refetch to update last_sync_at
      const data = await getForgejoRepositories();
      setRepositories(data);
      return result;
    } catch (err) {
      setNotice({
        tone: "error",
        message:
          err instanceof Error ? err.message : "Failed to sync repository",
      });
      throw err;
    }
  };

  const handleValidateRepository = async (repository: ForgejoRepository) => {
    try {
      const result = await validateRepository(repository.id);
      if (result.status.ok) {
        setNotice({
          tone: "success",
          message: `${repositoryName(repository)} is reachable from Pipeline.`,
        });
      } else {
        setNotice({
          tone: "error",
          message: `Repository validation failed: ${result.status.error_message || "Unknown error"}`,
        });
      }
      return result;
    } catch (err) {
      setNotice({
        tone: "error",
        message:
          err instanceof Error ? err.message : "Failed to validate repository",
      });
      throw err;
    }
  };

  return (
    <>
      <DashboardPageLayout
        signedOut={{
          message: "Sign in to manage Git Project repositories.",
          forceRedirectUrl: "/git-projects/repositories",
          signUpForceRedirectUrl: "/git-projects/repositories",
        }}
        title="Git Project Repositories"
        description={`${repositories.length} repositor${repositories.length === 1 ? "y" : "ies"} tracked by Pipeline.`}
        stickyHeader
      >
        <div className="flex flex-col gap-4">
          {notice ? (
            <div
              className={`flex items-start gap-3 rounded-xl border p-3 text-sm ${
                notice.tone === "success"
                  ? "border-[color:rgba(52,211,153,0.35)] bg-[color:rgba(52,211,153,0.08)] text-[color:var(--success)]"
                  : "border-[color:rgba(248,113,113,0.35)] bg-[color:rgba(248,113,113,0.08)] text-[color:var(--danger)]"
              }`}
            >
              {notice.tone === "success" ? (
                <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0" />
              ) : (
                <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
              )}
              <span>{notice.message}</span>
            </div>
          ) : null}

          <div className="flex flex-wrap items-center justify-between gap-3">
            <h2 className="text-sm font-medium text-muted">Repositories</h2>
            <Button
              onClick={() => router.push("/git-projects/repositories/new")}
            >
              Add Repository
            </Button>
          </div>
          <div className="overflow-hidden rounded-xl border border-[color:var(--border)] bg-[color:var(--surface)] shadow-lush">
            {error ? (
              <div className="p-8 text-center">
                <p className="text-sm text-[color:var(--danger)]">{error}</p>
              </div>
            ) : (
              <ForgejoRepositoriesTable
                repositories={repositories}
                isLoading={isLoading}
                onDelete={handleDelete}
                onSync={handleSync}
                onValidate={handleValidateRepository}
              />
            )}
          </div>
        </div>
      </DashboardPageLayout>
      <ConfirmActionDialog
        open={Boolean(deleteTarget)}
        onOpenChange={(open) => {
          if (!open) setDeleteTarget(null);
        }}
        title="Delete Git Project repository"
        description={
          deleteTarget
            ? `Delete "${repositoryName(deleteTarget)}" from Pipeline? Synced issue records for this repository will be removed.`
            : ""
        }
        onConfirm={confirmDelete}
        isConfirming={isDeleting}
        errorMessage={deleteError}
        confirmLabel="Delete Repository"
        confirmingLabel="Deleting…"
        confirmClassName="bg-destructive text-destructive-foreground hover:bg-destructive/90"
        cancelLabel="Keep Repository"
      />
    </>
  );
}
