package main

import (
	"fmt"

	"github.com/stephenafamo/bob"
	. "maragu.dev/gomponents"
	ds "maragu.dev/gomponents-datastar"
	. "maragu.dev/gomponents/components"
	. "maragu.dev/gomponents/html"
)

type Service struct {
	Name   string
	URL    string
	Status string
	Err    error
}

type State struct {
	Input  []string
	Mysql  *Service
	Theme  Theme
	Report [][]string
	Err    error
	db     bob.DB
}

type Theme string

const (
	ThemeLight = "light"
	ThemeDark  = "dark"
)

func Home(s *State) Node {
	main := Div(
		Class("grid"),
		input(s),
		mysql(s),
	)
	return layout("Home", s, main)
}

func Report(s *State) Node {
	if s.Report == nil {
		return layout("Report", s, Div(
			err(s.Err),
			Button(Text("Launch script")),
		))
	}

	table := Table(
		Map(s.Report, func(row []string) Node {
			return Tr(
				Map(row, func(cell string) Node {
					return Td(Text(cell))
				}),
			)
		}),
	)

	return layout("Report", s, table)
}

func input(s *State) Node {
	if len(s.Input) == 0 {
		return Article(
			Header(Text("Input")),
			P(Text("AIP Names")),
			Label(
				Input(
					Type("file"),
					Accept(".csv"),
					ds.Bind("input-file"),
				),
				Small(Text("only .csv files accepted - max size 1 MIB")),
			),
			Button(
				Type("submit"),
				Text("Upload Input file"),
				ds.On("click", "@post('/upload')"),
			),
		)
	} else {
		return Article(
			Header(Text(fmt.Sprintf("Input file has %d names", len(s.Input)))),
			Map(s.Input, func(id string) Node {
				return P(Text(id))
			}),
		)
	}
}

func mysql(s *State) Node {
	if s.Mysql.Status == "Disconnected" {
		return Article(
			Header(Text("Mysql Config")),
			Form(
				Action("/mysql"),
				Method("post"),
				FieldSet(
					Role("group"),
					Input(
						Type("text"),
						Name("mysql"),
						Placeholder("place mysql connection string here"),
					),
					Input(
						Type("submit"),
						Value("connect"),
					),
				),
			),
			Footer(err(s.Mysql.Err)),
		)
	}

	return Article(
		Header(Text("Mysql Config")),
		P(Text(fmt.Sprintf("Mysql Status: %s", s.Mysql.Status))),
		P(Text(fmt.Sprintf("Mysql URL: %s", s.Mysql.URL))),
	)
}

func err(err error) Node {
	if err != nil {
		return P(Text(err.Error()))
	}
	return nil
}

func layout(title string, s *State, children ...Node) Node {
	return HTML5(HTML5Props{
		Title:    "Migrate - " + title,
		Language: "en",
		Head: []Node{
			Link(Rel("stylesheet"), Href("/assets/css/pico.css")),
			Script(Type("module"), Src("https://cdn.jsdelivr.net/gh/starfederation/datastar@1.0.0-RC.7/bundles/datastar.js")),
		},
		Body: []Node{
			Class("container"),
			Header(
				H1(Text("AIPs Report")),
				Nav(
					Ul(
						navElement("/", "Config"),
						navElement("/report", "Report"),
					),
				),
			),
			Main(Group(children)),
			Footer(),
		},
		HTMLAttrs: []Node{
			Data("theme", string(s.Theme)),
		},
	},
	)
}

func navElement(path, name string) Node {
	return Li(A(Href(path), Text(name)))
}
