"use client";

import { useState } from "react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Loader2 } from "lucide-react";

import type { ForgejoConnectionCreate } from "@/lib/api-forgejo";

interface ForgejoConnectionFormProps {
  defaultValues?: Partial<ForgejoConnectionFormValues>;
  onSubmit: (values: ForgejoConnectionCreate) => Promise<void>;
  isSubmitting?: boolean;
  isTokenRequired?: boolean;
  existingTokenLastEight?: string | null;
  title?: string;
  description?: string;
  submitLabel?: string;
}

export interface ForgejoConnectionFormValues {
  name: string;
  base_url: string;
  token: string;
}

export function ForgejoConnectionForm({
  defaultValues = {},
  onSubmit,
  isSubmitting = false,
  isTokenRequired = true,
  existingTokenLastEight,
  title = "Git Project Connection",
  description = "Connect a Git provider so Pipeline can track issues.",
  submitLabel = "Save Connection",
}: ForgejoConnectionFormProps) {
  const [error, setError] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [name, setName] = useState(defaultValues.name || "");
  const [baseUrl, setBaseUrl] = useState(defaultValues.base_url || "");
  const [token, setToken] = useState(defaultValues.token || "");
  const isBusy = isSubmitting || isSaving;
  const tokenHelpText = isTokenRequired
    ? "Paste your Git provider personal access token. Use read:issue; add write:issue if Pipeline should close issues. The token is stored server-side and never displayed."
    : existingTokenLastEight
      ? `Leave blank to keep the saved token ending in ${existingTokenLastEight}. Paste a new token to replace it.`
      : "Paste a new Git provider personal access token to replace the saved token.";

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);

    try {
      setIsSaving(true);
      await onSubmit({
        name,
        base_url: baseUrl,
        token,
      });
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="surface-panel w-full max-w-2xl space-y-6 rounded-2xl p-4 sm:p-6"
    >
      <div className="space-y-4">
        <div>
          <h3 className="text-lg font-semibold text-strong">{title}</h3>
          {description && (
            <p className="mt-1 text-sm text-muted">{description}</p>
          )}
        </div>

        {error && (
          <div className="rounded-xl border border-[color:rgba(248,113,113,0.35)] bg-[color:rgba(248,113,113,0.08)] p-4 text-[color:var(--danger)]">
            <p className="font-medium">Configuration Error</p>
            <p className="text-sm">{error}</p>
          </div>
        )}

        <div className="space-y-2">
          <label htmlFor="name" className="text-sm font-medium">
            Name
          </label>
          <Input
            id="name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Team Git"
            disabled={isBusy}
            required
          />
          <p className="text-xs text-muted">
            A memorable name for this Git Projects connection.
          </p>
        </div>

        <div className="space-y-2">
          <label htmlFor="base_url" className="text-sm font-medium">
            Base URL
          </label>
          <Input
            id="base_url"
            value={baseUrl}
            onChange={(e) => setBaseUrl(e.target.value)}
            placeholder="https://git.example.com"
            disabled={isBusy}
            required
          />
          <p className="text-xs text-muted">
            The base URL of your Git provider instance, without a trailing
            slash.
          </p>
        </div>

        <div className="space-y-2">
          <label htmlFor="token" className="text-sm font-medium">
            Token
          </label>
          <Input
            id="token"
            type="password"
            value={token}
            onChange={(e) => setToken(e.target.value)}
            placeholder={
              isTokenRequired
                ? "Paste token"
                : existingTokenLastEight
                  ? `Current token ends in ${existingTokenLastEight}`
                  : "Paste token"
            }
            disabled={isBusy}
            required={isTokenRequired}
          />
          <p className="text-xs text-muted">{tokenHelpText}</p>
        </div>
      </div>

      <div className="flex flex-col-reverse gap-3 border-t border-[color:var(--border)] pt-4 sm:flex-row sm:justify-end">
        <Button
          type="button"
          variant="outline"
          onClick={() => window.history.back()}
          disabled={isBusy}
        >
          Cancel
        </Button>
        <Button type="submit" disabled={isBusy}>
          {isBusy ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Saving…
            </>
          ) : (
            submitLabel
          )}
        </Button>
      </div>
    </form>
  );
}
