"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 { ForgejoConnectionForm } from "@/components/git/ForgejoConnectionForm";
import { ConfirmActionDialog } from "@/components/ui/confirm-action-dialog";
import {
  getForgejoConnection,
  updateForgejoConnection,
  deleteForgejoConnection,
  type ForgejoConnectionUpdate,
} from "@/lib/api-forgejo";

interface RouteParams {
  connectionId: string;
}

interface ConnectionData {
  name: string;
  base_url: string;
  active: boolean;
  has_token: boolean;
  token_last_eight: string | null;
  id: string;
}

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

  const [connection, setConnection] = useState<ConnectionData | 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 fetchConnection = async () => {
      try {
        setIsLoading(true);
        const data = await getForgejoConnection(params.connectionId);
        setConnection(data);
        setError(null);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load connection",
        );
      } finally {
        setIsLoading(false);
      }
    };

    if (auth.isSignedIn) {
      fetchConnection();
    }
  }, [params.connectionId, auth.isSignedIn]);

  const handleSubmit = async (values: ForgejoConnectionUpdate) => {
    await updateForgejoConnection(params.connectionId, values);
    router.push("/git-projects/connections");
  };

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

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

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

  const defaultValues = {
    name: connection.name,
    base_url: connection.base_url,
    token: "",
  };

  return (
    <DashboardPageLayout
      signedOut={{
        message: "Sign in to edit a Git Project connection.",
        forceRedirectUrl: "/git-projects/connections",
        signUpForceRedirectUrl: "/git-projects/connections",
      }}
      title={`Edit Git Project Connection: ${connection.name}`}
      description="Update the Git provider settings Pipeline uses for Git Projects."
      stickyHeader
    >
      <div className="w-full max-w-2xl">
        <ForgejoConnectionForm
          defaultValues={defaultValues}
          onSubmit={handleSubmit}
          isTokenRequired={!connection.has_token}
          existingTokenLastEight={connection.token_last_eight}
          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 Connection
          </h3>
          <p className="mt-2 text-sm text-muted">
            Remove this connection from Pipeline. Repositories that use it will
            stop syncing.
          </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 Connection
          </Button>
        </div>
      </div>
      <ConfirmActionDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        title="Delete Git Project connection"
        description={`Delete "${connection.name}" from Pipeline? Tracked repositories and cached issues that use this connection will be removed.`}
        onConfirm={handleDelete}
        isConfirming={isDeleting}
        errorMessage={deleteError}
        confirmLabel="Delete Connection"
        confirmingLabel="Deleting…"
        confirmClassName="bg-destructive text-destructive-foreground hover:bg-destructive/90"
        cancelLabel="Keep Connection"
      />
    </DashboardPageLayout>
  );
}
