"use client";

import { use, useEffect, useState } from "react";
import { useRouter } from "next/navigation";

import { Button } from "@/components/ui/button";
import { useAuth } from "@/auth/clerk";
import { DashboardPageLayout } from "@/components/templates/DashboardPageLayout";
import { ForgejoRepositoryForm } from "@/components/git/ForgejoRepositoryForm";
import { ConfirmActionDialog } from "@/components/ui/confirm-action-dialog";
import {
  getForgejoRepository,
  updateForgejoRepository,
  deleteForgejoRepository,
  type ForgejoRepositoryUpdate,
} from "@/lib/api-forgejo";

interface RouteParams {
  repositoryId: string;
}

interface RepositoryData {
  id: string;
  connection_id: string;
  owner: string;
  repo: string;
  display_name: string;
  default_branch: string;
  active: boolean;
  connection: {
    id: string;
    name: string;
    base_url: string;
  };
}

export default function ForgejoRepositoriesEditPage({
  params: rawParams,
}: {
  params: Promise<RouteParams>;
}) {
  const params = use(rawParams);
  const router = useRouter();
  const auth = useAuth();

  const [repository, setRepository] = useState<RepositoryData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  useEffect(() => {
    const fetchRepository = async () => {
      try {
        setIsLoading(true);
        const data = await getForgejoRepository(params.repositoryId);
        setRepository(data);
        setError(null);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load repository",
        );
      } finally {
        setIsLoading(false);
      }
    };

    if (auth.isSignedIn) {
      fetchRepository();
    }
  }, [params.repositoryId, auth.isSignedIn]);

  const handleSubmit = async (values: ForgejoRepositoryUpdate) => {
    await updateForgejoRepository(params.repositoryId, values);
    router.push("/git-projects/repositories");
  };

  const handleDelete = async () => {
    setIsDeleting(true);
    setDeleteError(null);
    try {
      await deleteForgejoRepository(params.repositoryId);
      router.push("/git-projects/repositories");
    } catch (err) {
      setDeleteError(
        err instanceof Error ? err.message : "Failed to delete repository",
      );
    } finally {
      setIsDeleting(false);
    }
  };

  if (isLoading) {
    return (
      <DashboardPageLayout
        signedOut={{
          message: "Sign in to edit a tracked repository.",
          forceRedirectUrl: "/git-projects/repositories",
          signUpForceRedirectUrl: "/git-projects/repositories",
        }}
        title="Loading…"
        stickyHeader
      >
        <p className="text-muted">Loading repository…</p>
      </DashboardPageLayout>
    );
  }

  if (error || !repository) {
    return (
      <DashboardPageLayout
        signedOut={{
          message: "Sign in to edit a tracked repository.",
          forceRedirectUrl: "/git-projects/repositories",
          signUpForceRedirectUrl: "/git-projects/repositories",
        }}
        title="Error"
        stickyHeader
      >
        <p className="text-[color:var(--danger)]">
          {error || "Repository not found"}
        </p>
      </DashboardPageLayout>
    );
  }

  const defaultValues = {
    connection_id: repository.connection_id,
    owner: repository.owner,
    repo: repository.repo,
    display_name: repository.display_name,
    default_branch: repository.default_branch,
    showWebhookSecret: true,
  };

  return (
    <DashboardPageLayout
      signedOut={{
        message: "Sign in to edit a tracked repository.",
        forceRedirectUrl: "/git-projects/repositories",
        signUpForceRedirectUrl: "/git-projects/repositories",
      }}
      title={`Edit Git Project Repository: ${repository.display_name || repository.repo}`}
      description="Update the repository settings Pipeline uses for Git Projects."
      stickyHeader
    >
      <div className="w-full max-w-2xl">
        <ForgejoRepositoryForm
          defaultValues={defaultValues}
          onSubmit={handleSubmit}
          submitLabel="Save Changes"
        />
        <div className="surface-muted mt-6 rounded-2xl p-4 sm:p-5">
          <h3 className="text-base font-semibold text-[color:var(--danger)]">
            Delete Repository
          </h3>
          <p className="mt-2 text-sm text-muted">
            Remove this repository from Pipeline. Synced issue records for this
            repository will be removed.
          </p>
          <Button
            variant="outline"
            className="mt-4 border-[color:rgba(248,113,113,0.45)] text-[color:var(--danger)] hover:bg-[color:rgba(248,113,113,0.08)]"
            onClick={() => setDeleteOpen(true)}
          >
            Delete Repository
          </Button>
        </div>
      </div>
      <ConfirmActionDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        title="Delete Git Project repository"
        description={`Delete "${repository.display_name || repository.repo}" from Pipeline? Synced issue records for this repository will be removed.`}
        onConfirm={handleDelete}
        isConfirming={isDeleting}
        errorMessage={deleteError}
        confirmLabel="Delete Repository"
        confirmingLabel="Deleting…"
        confirmClassName="bg-destructive text-destructive-foreground hover:bg-destructive/90"
        cancelLabel="Keep Repository"
      />
    </DashboardPageLayout>
  );
}
