package pkg

import (
	"context"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"html/template"
	"math"
	"net/http"
	"strconv"
	"strings"
)

type ProductEntry struct {
	Slug  string
	Name  string
	Price string
	Tags  []string
}

type productsIndexPage struct {
	Products []*ProductEntry
	Filters  *productFilterForm
}

func IndexProducts(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	conn := getConn(r)
	company := mustGetCompany(r)
	locale := getLocale(r)
	filters := newProductFilterForm(locale)
	if err := filters.Parse(r); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	page := &productsIndexPage{
		Products: mustCollectProductEntries(r.Context(), conn, company, filters),
		Filters:  filters,
	}
	mustRenderMainTemplate(w, r, "products/index.gohtml", page)
}

func GetProductForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	locale := getLocale(r)
	conn := getConn(r)
	company := mustGetCompany(r)
	form := newProductForm(r.Context(), conn, locale, company)
	slug := params[0].Value
	if slug == "new" {
		w.WriteHeader(http.StatusOK)
		mustRenderNewProductForm(w, r, form)
		return
	}
	if !form.MustFillFromDatabase(r.Context(), conn, slug) {
		http.NotFound(w, r)
		return
	}
	w.WriteHeader(http.StatusOK)
	mustRenderEditProductForm(w, r, slug, form)
}

func mustRenderNewProductForm(w http.ResponseWriter, r *http.Request, form *productForm) {
	mustRenderMainTemplate(w, r, "products/new.gohtml", form)
}

type editProductPage struct {
	Slug        string
	ProductName string
	Form        *productForm
}

func mustRenderEditProductForm(w http.ResponseWriter, r *http.Request, slug string, form *productForm) {
	page := &editProductPage{
		Slug:        slug,
		ProductName: form.Name.Val,
		Form:        form,
	}
	mustRenderMainTemplate(w, r, "products/edit.gohtml", page)
}

func HandleAddProduct(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	conn := getConn(r)
	locale := getLocale(r)
	company := mustGetCompany(r)
	form := newProductForm(r.Context(), conn, locale, company)
	if err := form.Parse(r); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if err := verifyCsrfTokenValid(r); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}
	if !form.Validate() {
		if !IsHTMxRequest(r) {
			w.WriteHeader(http.StatusUnprocessableEntity)
		}
		mustRenderNewProductForm(w, r, form)
		return
	}
	taxes := mustSliceAtoi(form.Tax.Selected)
	conn.MustExec(r.Context(), "select add_product($1, $2, $3, $4, $5, $6)", company.Id, form.Name, form.Description, form.Price, taxes, form.Tags)
	htmxRedirect(w, r, companyURI(company, "/products"))
}

func sliceAtoi(s []string) ([]int, error) {
	var i []int
	for _, vs := range s {
		vi, err := strconv.Atoi(vs)
		if err != nil {
			return i, err
		}
		i = append(i, vi)
	}
	return i, nil
}

func mustSliceAtoi(s []string) []int {
	i, err := sliceAtoi(s)
	if err != nil {
		panic(err)
	}
	return i
}

func HandleUpdateProduct(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	conn := getConn(r)
	locale := getLocale(r)
	company := mustGetCompany(r)
	form := newProductForm(r.Context(), conn, locale, company)
	if err := form.Parse(r); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if err := verifyCsrfTokenValid(r); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}
	slug := params[0].Value
	if !form.Validate() {
		if !IsHTMxRequest(r) {
			w.WriteHeader(http.StatusUnprocessableEntity)
		}
		mustRenderEditProductForm(w, r, slug, form)
		return
	}
	taxes := mustSliceAtoi(form.Tax.Selected)
	if ok := conn.MustGetBool(r.Context(), "select edit_product($1, $2, $3, $4, $5, $6)", slug, form.Name, form.Description, form.Price, taxes, form.Tags); !ok {
		http.NotFound(w, r)
		return
	}
	htmxRedirect(w, r, companyURI(company, "/products"))
}

type productFilterForm struct {
	Name          *InputField
	Tags          *TagsField
	TagsCondition *ToggleField
}

func newProductFilterForm(locale *Locale) *productFilterForm {
	return &productFilterForm{
		Name: &InputField{
			Name:  "number",
			Label: pgettext("input", "Name", locale),
			Type:  "search",
		},
		Tags: &TagsField{
			Name:  "tags",
			Label: pgettext("input", "Tags", locale),
		},
		TagsCondition: &ToggleField{
			Name:     "tags_condition",
			Label:    pgettext("input", "Tags Condition", locale),
			Selected: "and",
			FirstOption: &ToggleOption{
				Value:       "and",
				Label:       pgettext("tag condition", "All", locale),
				Description: gettext("Invoices must have all the specified labels.", locale),
			},
			SecondOption: &ToggleOption{
				Value:       "or",
				Label:       pgettext("tag condition", "Any", locale),
				Description: gettext("Invoices must have at least one of the specified labels.", locale),
			},
		},
	}
}

func (form *productFilterForm) Parse(r *http.Request) error {
	if err := r.ParseForm(); err != nil {
		return err
	}
	form.Name.FillValue(r)
	form.Tags.FillValue(r)
	form.TagsCondition.FillValue(r)
	return nil
}

func mustCollectProductEntries(ctx context.Context, conn *Conn, company *Company, filters *productFilterForm) []*ProductEntry {
	args := []interface{}{company.Id}
	where := []string{"product.company_id = $1"}
	appendWhere := func(expression string, value interface{}) {
		args = append(args, value)
		where = append(where, fmt.Sprintf(expression, len(args)))
	}
	if filters != nil {
		name := strings.TrimSpace(filters.Name.String())
		if name != "" {
			appendWhere("product.name ilike $%d", "%"+name+"%")
		}
		if len(filters.Tags.Tags) > 0 {
			if filters.TagsCondition.Selected == "and" {
				appendWhere("product.tags @> $%d", filters.Tags)
			} else {
				appendWhere("product.tags && $%d", filters.Tags)
			}
		}
	}
	rows := conn.MustQuery(ctx, fmt.Sprintf(`
		select product.slug
		     , product.name
		     , to_price(price, decimal_digits)
		     , tags
		from product
		join company using (company_id)
		join currency using (currency_code)
		where (%s)
		order by name
	`, strings.Join(where, ") AND (")), args...)
	defer rows.Close()

	var entries []*ProductEntry
	for rows.Next() {
		entry := &ProductEntry{}
		if err := rows.Scan(&entry.Slug, &entry.Name, &entry.Price, &entry.Tags); err != nil {
			panic(err)
		}
		entries = append(entries, entry)
	}
	if rows.Err() != nil {
		panic(rows.Err())
	}

	return entries
}

type productForm struct {
	locale      *Locale
	company     *Company
	Name        *InputField
	Description *InputField
	Price       *InputField
	Tax         *SelectField
	Tags        *TagsField
}

func newProductForm(ctx context.Context, conn *Conn, locale *Locale, company *Company) *productForm {
	return &productForm{
		locale:  locale,
		company: company,
		Name: &InputField{
			Name:     "name",
			Label:    pgettext("input", "Name", locale),
			Type:     "text",
			Required: true,
		},
		Description: &InputField{
			Name:  "description",
			Label: pgettext("input", "Description", locale),
			Type:  "textarea",
		},
		Price: &InputField{
			Name:     "price",
			Label:    pgettext("input", "Price", locale),
			Type:     "number",
			Required: true,
			Attributes: []template.HTMLAttr{
				`min="0"`,
				template.HTMLAttr(fmt.Sprintf(`step="%v"`, company.MinCents())),
			},
		},
		Tax: &SelectField{
			Name:     "tax",
			Label:    pgettext("input", "Taxes", locale),
			Multiple: true,
			Options:  mustGetTaxOptions(ctx, conn, company),
		},
		Tags: &TagsField{
			Name:  "tags",
			Label: pgettext("input", "Tags", locale),
		},
	}
}

func (form *productForm) Parse(r *http.Request) error {
	if err := r.ParseForm(); err != nil {
		return err
	}
	form.Name.FillValue(r)
	form.Description.FillValue(r)
	form.Price.FillValue(r)
	form.Tax.FillValue(r)
	form.Tags.FillValue(r)
	return nil
}

func (form *productForm) Validate() bool {
	validator := newFormValidator()
	validator.CheckRequiredInput(form.Name, gettext("Name can not be empty.", form.locale))
	if validator.CheckRequiredInput(form.Price, gettext("Price can not be empty.", form.locale)) {
		validator.CheckValidDecimal(form.Price, form.company.MinCents(), math.MaxFloat64, gettext("Price must be a number greater than zero.", form.locale))
	}
	validator.CheckValidSelectOption(form.Tax, gettext("Selected tax is not valid.", form.locale))
	validator.CheckAtMostOneOfEachGroup(form.Tax, gettext("You can only select a tax of each class.", form.locale))
	return validator.AllOK()
}

func (form *productForm) MustFillFromDatabase(ctx context.Context, conn *Conn, slug string) bool {
	return !notFoundErrorOrPanic(conn.QueryRow(ctx, `
		select product.name
		     , product.description
		     , to_price(price, decimal_digits)
		     , array_agg(tax_id)
		     , tags
		from product
		left join product_tax using (product_id)
		join company using (company_id)
		join currency using (currency_code)
		where product.slug = $1
		group by product_id
		       , product.name
		       , product.description
		       , price
		       , tags
		       , decimal_digits
	`, slug).Scan(
		form.Name,
		form.Description,
		form.Price,
		form.Tax,
		form.Tags))
}

func HandleProductSearch(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	filters := newProductFilterForm(getLocale(r))
	query := r.URL.Query()
	index := query.Get("index")
	filters.Name.Val = strings.TrimSpace(query.Get("product.name." + index))
	var products []*ProductEntry
	if len(filters.Name.Val) > 0 {
		products = mustCollectProductEntries(r.Context(), getConn(r), mustGetCompany(r), filters)
	}
	mustRenderStandaloneTemplate(w, r, "products/search.gohtml", products)
}

func ServeEditProductTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	conn := getConn(r)
	locale := getLocale(r)
	company := getCompany(r)
	slug := params[0].Value
	form := newTagsForm(companyURI(company, "/products/"+slug+"/tags"), slug, locale)
	if notFoundErrorOrPanic(conn.QueryRow(r.Context(), `select tags from product where slug = $1`, form.Slug).Scan(form.Tags)) {
		http.NotFound(w, r)
		return
	}
	mustRenderStandaloneTemplate(w, r, "tags/edit.gohtml", form)
}

func HandleUpdateProductTags(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	locale := getLocale(r)
	conn := getConn(r)
	company := getCompany(r)
	slug := params[0].Value
	form := newTagsForm(companyURI(company, "/products/"+slug+"/tags/edit"), slug, locale)
	if err := form.Parse(r); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if err := verifyCsrfTokenValid(r); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}
	if conn.MustGetText(r.Context(), "", "update product set tags = $1 where slug = $2 returning slug", form.Tags, form.Slug) == "" {
		http.NotFound(w, r)
	}
	mustRenderStandaloneTemplate(w, r, "tags/view.gohtml", form)
}
