package ui

import (
	"fmt"
	"log"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"

	"MobileMkch/models"
)

type BoardsScreen struct {
	uiManager *UIManager
	content   *fyne.Container
	boards    []models.Board
	loading   bool
}

func NewBoardsScreen(uiManager *UIManager) *BoardsScreen {
	screen := &BoardsScreen{
		uiManager: uiManager,
		loading:   false,
	}

	screen.setupContent()
	return screen
}

func (bs *BoardsScreen) setupContent() {
	bs.content = container.NewVBox()

	header := widget.NewLabel("Выберите доску:")
	header.TextStyle = fyne.TextStyle{Bold: true}
	bs.content.Add(header)

	bs.content.Add(widget.NewLabel("Загрузка досок..."))

}

func (bs *BoardsScreen) GetContent() fyne.CanvasObject {
	return bs.content
}

func (bs *BoardsScreen) GetTitle() string {
	return "MobileMkch - Доски"
}

func (bs *BoardsScreen) OnShow() {
	if !bs.loading {
		bs.loadBoards()
	}
}

func (bs *BoardsScreen) OnHide() {
	// Ничего не делаем
}

func (bs *BoardsScreen) loadBoards() {
	bs.loading = true
	bs.showLoading()
	go func() {
		defer func() {
			bs.loading = false
		}()

		boards, err := bs.uiManager.GetAPIClient().GetBoards()
		if err != nil {
			log.Printf("Ошибка загрузки досок: %v", err)
			fyne.Do(func() {
				bs.showError(fmt.Sprintf("Ошибка загрузки досок:\n%v", err))
			})
			return
		}

		bs.boards = boards

		fyne.Do(func() {
			bs.displayBoards()
		})
	}()
}

func (bs *BoardsScreen) showLoading() {
	bs.content.RemoveAll()

	header := widget.NewLabel("Доски mkch")
	header.TextStyle = fyne.TextStyle{Bold: true}
	bs.content.Add(header)

	progressBar := widget.NewProgressBarInfinite()
	bs.content.Add(progressBar)
	progressBar.Start()

	bs.content.Add(widget.NewLabel("Загрузка досок..."))

	bs.content.Refresh()
}

func (bs *BoardsScreen) showError(message string) {
	bs.content.RemoveAll()

	header := widget.NewLabel("Доски mkch")
	header.TextStyle = fyne.TextStyle{Bold: true}
	bs.content.Add(header)

	errorLabel := widget.NewLabel("❌ " + message)
	errorLabel.Wrapping = fyne.TextWrapWord
	bs.content.Add(errorLabel)

	retryButton := widget.NewButton("Повторить", func() {
		bs.loadBoards()
	})
	bs.content.Add(retryButton)

	bs.content.Refresh()
}

func (bs *BoardsScreen) displayBoards() {
	bs.content.RemoveAll()

	header := widget.NewLabel("Доски mkch")
	header.TextStyle = fyne.TextStyle{Bold: true}
	bs.content.Add(header)

	if len(bs.boards) == 0 {
		emptyLabel := widget.NewLabel("Досок не найдено")
		bs.content.Add(emptyLabel)
		bs.content.Refresh()
		return
	}

	for i := range bs.boards {
		board := bs.boards[i]

		boardButton := bs.createBoardCard(&board)
		bs.content.Add(boardButton)
	}

	bs.content.Refresh()
}

func (bs *BoardsScreen) createBoardCard(board *models.Board) fyne.CanvasObject {
	title := fmt.Sprintf("/%s/", board.Code)

	description := board.Description
	if description == "" {
		description = "Без описания"
	}

	button := widget.NewButton(fmt.Sprintf("%s\n%s", title, description), func() {
		bs.uiManager.SetLastBoard(board.Code)
		bs.uiManager.ShowBoardThreads(board)
	})

	return button
}

func (bs *BoardsScreen) RefreshBoards() {
	bs.loadBoards()
}
