"use client";

import { useEffect, useState } from "react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Loader2 } from "lucide-react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

import {
  getForgejoConnections,
  type ForgejoConnection,
  type ForgejoRepositoryCreate,
} from "@/lib/api-forgejo";

interface ForgejoRepositoryFormProps {
  defaultValues?: Partial<ForgejoRepositoryFormValues>;
  onSubmit: (values: ForgejoRepositoryCreate) => Promise<void>;
  isSubmitting?: boolean;
  title?: string;
  description?: string;
  submitLabel?: string;
}

export interface ForgejoRepositoryFormValues {
  connection_id: string;
  owner: string;
  repo: string;
  display_name?: string;
  default_branch?: string;
}

export function ForgejoRepositoryForm({
  defaultValues = {},
  onSubmit,
  isSubmitting = false,
  title = "Tracked Repository",
  description = "Add a repository to track issues and pull requests.",
  submitLabel = "Save Repository",
}: ForgejoRepositoryFormProps) {
  const [error, setError] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [connectionId, setConnectionId] = useState(
    defaultValues.connection_id || "",
  );
  const [owner, setOwner] = useState(defaultValues.owner || "");
  const [repo, setRepo] = useState(defaultValues.repo || "");
  const [displayName, setDisplayName] = useState(
    defaultValues.display_name || "",
  );
  const [defaultBranch, setDefaultBranch] = useState(
    defaultValues.default_branch || "main",
  );

  // Get connections for dropdown
  const [connections, setConnections] = useState<ForgejoConnection[]>([]);

  const [isLoadingConnections, setIsLoadingConnections] = useState(false);
  const isBusy = isSubmitting || isSaving;

  useEffect(() => {
    const fetchConnections = async () => {
      try {
        setIsLoadingConnections(true);
        const data = await getForgejoConnections();
        setConnections(data.filter((connection) => connection.active));
      } catch {
        setError("Failed to load connections");
      } finally {
        setIsLoadingConnections(false);
      }
    };
    fetchConnections();
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    if (!connectionId) {
      setError(
        "Choose a Git Projects connection before saving this repository.",
      );
      return;
    }

    try {
      setIsSaving(true);
      await onSubmit({
        connection_id: connectionId,
        owner,
        repo,
        display_name: displayName || undefined,
        default_branch: defaultBranch,
      });
    } 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="connection_id" className="text-sm font-medium">
            Connection
          </label>
          <Select
            value={connectionId}
            onValueChange={setConnectionId}
            disabled={
              isBusy || isLoadingConnections || connections.length === 0
            }
          >
            <SelectTrigger id="connection_id">
              <SelectValue
                placeholder={
                  isLoadingConnections
                    ? "Loading connections…"
                    : "Select a connection"
                }
              />
            </SelectTrigger>
            <SelectContent>
              {connections.map((conn) => (
                <SelectItem key={conn.id} value={conn.id}>
                  {conn.name} - {conn.base_url}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <p className="text-xs text-muted">
            The Git Projects connection to use for this repository. Add a
            connection first if none are available.
          </p>
        </div>

        <div className="grid gap-4 sm:grid-cols-2">
          <div className="space-y-2">
            <label htmlFor="owner" className="text-sm font-medium">
              Owner
            </label>
            <Input
              id="owner"
              value={owner}
              onChange={(e) => setOwner(e.target.value)}
              placeholder="openclaw"
              disabled={isBusy}
              required
            />
            <p className="text-xs text-muted">
              The owner of the repository (username or organization).
            </p>
          </div>

          <div className="space-y-2">
            <label htmlFor="repo" className="text-sm font-medium">
              Repository
            </label>
            <Input
              id="repo"
              value={repo}
              onChange={(e) => setRepo(e.target.value)}
              placeholder="pipeline"
              disabled={isBusy}
              required
            />
            <p className="text-xs text-muted">The name of the repository.</p>
          </div>
        </div>

        <div className="space-y-2">
          <label htmlFor="display_name" className="text-sm font-medium">
            Display Name (Optional)
          </label>
          <Input
            id="display_name"
            value={displayName}
            onChange={(e) => setDisplayName(e.target.value)}
            placeholder="Pipeline"
            disabled={isBusy}
          />
          <p className="text-xs text-muted">
            A friendly name for this repository. If not provided, the owner/repo
            will be used.
          </p>
        </div>

        <div className="space-y-2">
          <label htmlFor="default_branch" className="text-sm font-medium">
            Default Branch
          </label>
          <Input
            id="default_branch"
            value={defaultBranch}
            onChange={(e) => setDefaultBranch(e.target.value)}
            placeholder="main"
            disabled={isBusy}
            required
          />
          <p className="text-xs text-muted">
            The default branch for this repository (e.g., main, dev, master).
          </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>
  );
}
