/** Form for creating a new workspace. */

import { useState } from "react";
import { Icon } from "./icon";
import type { CreateWorkspaceRequest } from "../types/workspace";

export interface WorkspaceCreateFormProps {
  projectId: string;
  repoId: string;
  defaultBranch?: string;
  onSubmit: (data: CreateWorkspaceRequest) => Promise<void>;
  onCancel: () => void;
}

export function WorkspaceCreateForm({
  defaultBranch = "main",
  onSubmit,
  onCancel,
}: WorkspaceCreateFormProps) {
  const [name, setName] = useState("");
  const [branch, setBranch] = useState(defaultBranch);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) {
      setError("Workspace name is required");
      return;
    }
    setSubmitting(true);
    setError(null);
    try {
      await onSubmit({ name: name.trim(), branch: branch.trim() });
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to create workspace");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <form className="workspace-create-form card" onSubmit={handleSubmit}>
      <h3>
        <Icon name="add" size="sm" /> Create Workspace
      </h3>
      <div className="form-group">
        <label htmlFor="ws-name">Name</label>
        <input
          id="ws-name"
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="e.g., feature-branch"
          disabled={submitting}
        />
      </div>
      <div className="form-group">
        <label htmlFor="ws-branch">
          <Icon name="branch" size="sm" /> Branch
        </label>
        <input
          id="ws-branch"
          type="text"
          value={branch}
          onChange={(e) => setBranch(e.target.value)}
          placeholder="main"
          disabled={submitting}
        />
      </div>
      {error && <p className="form-error">{error}</p>}
      <div className="form-actions">
        <button type="button" className="btn btn-secondary" onClick={onCancel} disabled={submitting}>
          Cancel
        </button>
        <button type="submit" className="btn btn-primary" disabled={submitting}>
          {submitting ? "Creating..." : "Create"}
        </button>
      </div>
    </form>
  );
}
