// Package create implements the label create command
package create

import (
	"fmt"
	"net/http"
	"regexp"

	"github.com/MakeNowJust/heredoc/v2"
	"github.com/spf13/cobra"

	"gitcode.com/gitcode-cli/cli/api"
	cmdutil "gitcode.com/gitcode-cli/cli/pkg/cmdutil"
	"gitcode.com/gitcode-cli/cli/pkg/iostreams"
)

type CreateOptions struct {
	IO         *iostreams.IOStreams
	HttpClient func() (*http.Client, error)
	BaseRepo   func() (string, error)

	// Arguments
	Repository string
	Name       string

	// Flags
	Color       string
	Description string
	JSON        bool
}

// NewCmdCreate creates the create command
func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Command {
	opts := &CreateOptions{
		IO:         f.IOStreams,
		HttpClient: f.HttpClient,
		BaseRepo:   f.BaseRepo,
	}

	cmd := &cobra.Command{
		Use:   "create <name>",
		Short: "Create a label",
		Long: heredoc.Doc(`
			Create a new label in a GitCode repository.
		`),
		Example: heredoc.Doc(`
			# Create a bug label
			$ gc label create bug --color "#ff0000" -R owner/repo

			# Create with description
			$ gc label create enhancement --color "#00ff00" --description "New features" -R owner/repo

			# Output as JSON
			$ gc label create bug --color "#ff0000" --json -R owner/repo
		`),
		Args: cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.Name = args[0]

			if runF != nil {
				return runF(opts)
			}
			return createRun(opts)
		},
	}

	cmd.Flags().StringVarP(&opts.Repository, "repo", "R", "", "Repository (owner/repo)")
	cmd.Flags().StringVarP(&opts.Color, "color", "c", "#ededed", "Color in hex format")
	cmd.Flags().StringVarP(&opts.Description, "description", "d", "", "Description")
	cmd.Flags().BoolVar(&opts.JSON, "json", false, "Output as JSON")

	return cmd
}

func createRun(opts *CreateOptions) error {
	if opts.Description != "" {
		if err := cmdutil.ScanContentForSecrets(opts.Description); err != nil {
			return err
		}
	}
	cs := opts.IO.ColorScheme()

	httpClient, err := opts.HttpClient()
	if err != nil {
		return fmt.Errorf("failed to create HTTP client: %w", err)
	}
	client, err := cmdutil.AuthenticatedClient(httpClient)
	if err != nil {
		return err
	}

	// Get repository
	repository, err := cmdutil.ResolveRepo(opts.Repository, opts.BaseRepo)
	if err != nil {
		return err
	}
	owner, repo, err := parseRepo(repository)
	if err != nil {
		return err
	}

	// Validate color format
	colorPattern := regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
	if !colorPattern.MatchString(opts.Color) {
		return cmdutil.NewUsageError("--color must be in hex format (e.g., #ff0000)")
	}

	// Create label
	label, err := api.CreateLabel(client, owner, repo, &api.CreateLabelOptions{
		Name:        opts.Name,
		Color:       opts.Color,
		Description: opts.Description,
	})
	if err != nil {
		return fmt.Errorf("failed to create label: %w", err)
	}

	if opts.JSON {
		return cmdutil.WriteJSON(opts.IO.Out, label)
	}

	fmt.Fprintf(opts.IO.Out, "%s Created label %s (ID: %s) in %s/%s\n", cs.Green("✓"), cs.Bold(label.Name), cmdutil.FormatAPIID(label.ID), owner, repo)
	return nil
}

func parseRepo(repo string) (string, string, error) {
	return cmdutil.ParseRepo(repo)
}