package views

import (
	"icdb/internal/ui/widgets"
	"icdb/pkg/layouts"
	"image/color"

	"gioui.org/layout"
	"gioui.org/text"
	"gioui.org/unit"
	"gioui.org/widget"
	"gioui.org/widget/material"
)

var (
	searchInput  widget.Editor
	searchButton widget.Clickable
	clearButton  widget.Clickable
)

// PartsView returns the widget for the parts view.
func PartsView(gtx layout.Context, th *material.Theme) layout.Dimensions {
	return layout.Flex{
		Axis:    layout.Vertical,
		Spacing: layout.SpaceEnd,
	}.Layout(gtx,
		layout.Rigid(func(gtx layout.Context) layout.Dimensions {
			title := material.H4(th, "Part Database")
			title.Alignment = text.Middle
			return title.Layout(gtx)
		}),
		layout.Rigid(layouts.FixedMaxSize(func(gtx layout.Context) layout.Dimensions {
			return layout.Flex{
				Alignment: layout.Alignment(layout.Center),
				Axis:      layout.Horizontal,
				Spacing:   layout.SpaceAround,
			}.Layout(gtx,
				layout.Rigid(renderSearchBar(th)),
			)
		}, gtx.Constraints.Max.X, 100)),
		layout.Rigid(func(gtx layout.Context) layout.Dimensions {
			return widgets.SeparatorHorizontal(gtx)
		}),
	)
}

// renderSearchBar returns the widget for the parts view search bar.
func renderSearchBar(th *material.Theme) layout.Widget {
	return func(gtx layout.Context) layout.Dimensions {
		return layout.Flex{
			Axis:    layout.Horizontal,
			Spacing: layout.SpaceBetween,
		}.Layout(gtx,
			// Clear button
			layout.Rigid(func(gtx layout.Context) layout.Dimensions {
				margins := layout.UniformInset(unit.Dp(10))
				btn := material.Button(th, &clearButton, "Clear")

				return margins.Layout(gtx,
					func(gtx layout.Context) layout.Dimensions {
						return btn.Layout(gtx)
					},
				)
			}),
			// Search bar input
			layout.Rigid(func(gtx layout.Context) layout.Dimensions {
				ed := material.Editor(th, &searchInput, "search")

				searchInput.SingleLine = true
				searchInput.Alignment = text.Middle

				margins := layout.UniformInset(unit.Dp(10))

				border := widget.Border{
					Color:        color.NRGBA{R: 204, G: 204, B: 204, A: 255},
					CornerRadius: unit.Dp(3),
					Width:        unit.Dp(2),
				}

				return margins.Layout(gtx,
					func(gtx layout.Context) layout.Dimensions {
						return border.Layout(gtx, layouts.FixedSize(ed.Layout, 300, 37))
					},
				)
			}),
			// Search button
			layout.Rigid(func(gtx layout.Context) layout.Dimensions {
				margins := layout.UniformInset(unit.Dp(10))
				btn := material.Button(th, &searchButton, "Search")

				return margins.Layout(gtx,
					func(gtx layout.Context) layout.Dimensions {
						return btn.Layout(gtx)
					},
				)
			}),
		)
	}
}
