package browser

import (
	"fmt"
	"os"
	"path/filepath"
)

// FillFormField fills a form field with the specified value
func (m *Manager) FillFormField(tabID, selector, value string) error {
	page, err := m.GetTab(tabID)
	if err != nil {
		return err
	}

	// Find the element
	element, err := page.Element(selector)
	if err != nil {
		return fmt.Errorf("failed to find element: %w", err)
	}

	// Clear the field first
	_ = element.SelectAllText()
	err = element.Input("")
	if err != nil {
		return fmt.Errorf("failed to clear field: %w", err)
	}

	// Input the value
	err = element.Input(value)
	if err != nil {
		return fmt.Errorf("failed to input value: %w", err)
	}

	return nil
}

// UploadFile uploads a file to a file input element
func (m *Manager) UploadFile(tabID, selector, filePath string) error {
	page, err := m.GetTab(tabID)
	if err != nil {
		return err
	}

	// Check if the file exists
	absPath, err := filepath.Abs(filePath)
	if err != nil {
		return fmt.Errorf("failed to get absolute path: %w", err)
	}

	_, err = os.Stat(absPath)
	if err != nil {
		return fmt.Errorf("file not found: %w", err)
	}

	// Find the file input element
	element, err := page.Element(selector)
	if err != nil {
		return fmt.Errorf("failed to find file input element: %w", err)
	}

	// Set the file
	err = element.SetFiles([]string{absPath})
	if err != nil {
		return fmt.Errorf("failed to set file: %w", err)
	}

	return nil
}

// SubmitForm submits a form
func (m *Manager) SubmitForm(tabID, selector string) error {
	page, err := m.GetTab(tabID)
	if err != nil {
		return err
	}

	// Find the form element
	form, err := page.Element(selector)
	if err != nil {
		return fmt.Errorf("failed to find form element: %w", err)
	}

	// Submit the form
	_, err = form.Eval(`() => this.submit()`)
	if err != nil {
		return fmt.Errorf("failed to submit form: %w", err)
	}

	// Wait for the page to load after form submission
	err = page.WaitLoad()
	if err != nil {
		return fmt.Errorf("failed to wait for page load after form submission: %w", err)
	}

	return nil
}
