package pkg

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

type ContactEntry struct {
	Slug  string
	Name  string
	Email string
	Phone string
	Tags  []string
}

type ContactsIndexPage struct {
	Contacts []*ContactEntry
	Filters  *contactFilterForm
}

func IndexContacts(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	conn := getConn(r)
	company := mustGetCompany(r)
	locale := getLocale(r)
	filters := newContactFilterForm(locale)
	if err := filters.Parse(r); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	page := &ContactsIndexPage{
		Contacts: mustCollectContactEntries(r.Context(), conn, company, filters),
		Filters:  filters,
	}
	mustRenderMainTemplate(w, r, "contacts/index.gohtml", page)
}

func GetContactForm(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	locale := getLocale(r)
	conn := getConn(r)
	form := newContactForm(r.Context(), conn, locale)
	slug := params[0].Value
	if slug == "new" {
		w.WriteHeader(http.StatusOK)
		mustRenderNewContactForm(w, r, form)
		return
	}
	if !form.MustFillFromDatabase(r.Context(), conn, slug) {
		http.NotFound(w, r)
		return
	}
	w.WriteHeader(http.StatusOK)
	mustRenderEditContactForm(w, r, slug, form)
}

func mustRenderNewContactForm(w http.ResponseWriter, r *http.Request, form *contactForm) {
	mustRenderMainTemplate(w, r, "contacts/new.gohtml", form)
}

type editContactPage struct {
	Slug        string
	ContactName string
	Form        *contactForm
}

func mustRenderEditContactForm(w http.ResponseWriter, r *http.Request, slug string, form *contactForm) {
	page := &editContactPage{
		Slug:        slug,
		ContactName: form.BusinessName.Val,
		Form:        form,
	}
	mustRenderMainTemplate(w, r, "contacts/edit.gohtml", page)
}

func HandleAddContact(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	conn := getConn(r)
	locale := getLocale(r)
	form := newContactForm(r.Context(), conn, 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 !form.Validate(r.Context(), conn) {
		if !IsHTMxRequest(r) {
			w.WriteHeader(http.StatusUnprocessableEntity)
		}
		mustRenderNewContactForm(w, r, form)
		return
	}
	company := mustGetCompany(r)
	conn.MustExec(r.Context(), "select add_contact($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)", company.Id, form.BusinessName, form.VATIN, form.TradeName, form.Phone, form.Email, form.Web, form.Address, form.City, form.Province, form.PostalCode, form.Country, form.Tags)
	htmxRedirect(w, r, companyURI(company, "/contacts"))
}

func HandleUpdateContact(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
	conn := getConn(r)
	locale := getLocale(r)
	form := newContactForm(r.Context(), conn, 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 !form.Validate(r.Context(), conn) {
		mustRenderEditContactForm(w, r, params[0].Value, form)
		return
	}
	slug := conn.MustGetText(r.Context(), "", "select edit_contact($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)", params[0].Value, form.BusinessName, form.VATIN, form.TradeName, form.Phone, form.Email, form.Web, form.Address, form.City, form.Province, form.PostalCode, form.Country, form.Tags)
	if slug == "" {
		http.NotFound(w, r)
	}
	htmxRedirect(w, r, companyURI(mustGetCompany(r), "/contacts"))
}

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

func newContactFilterForm(locale *Locale) *contactFilterForm {
	return &contactFilterForm{
		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 *contactFilterForm) 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 mustCollectContactEntries(ctx context.Context, conn *Conn, company *Company, filters *contactFilterForm) []*ContactEntry {
	args := []interface{}{company.Id}
	where := []string{"contact.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("contact.business_name ilike $%d", "%"+name+"%")
		}
		if len(filters.Tags.Tags) > 0 {
			if filters.TagsCondition.Selected == "and" {
				appendWhere("contact.tags @> $%d", filters.Tags)
			} else {
				appendWhere("contact.tags && $%d", filters.Tags)
			}
		}
	}
	rows := conn.MustQuery(ctx, fmt.Sprintf(`
		select slug
		     , business_name
		     , email
		     , phone
		     , tags
		from contact
		where (%s)
		order by business_name
	`, strings.Join(where, ") AND (")), args...)
	defer rows.Close()

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

	return entries
}

type contactForm struct {
	locale       *Locale
	BusinessName *InputField
	VATIN        *InputField
	TradeName    *InputField
	Phone        *InputField
	Email        *InputField
	Web          *InputField
	Address      *InputField
	City         *InputField
	Province     *InputField
	PostalCode   *InputField
	Country      *SelectField
	Tags         *TagsField
}

func newContactForm(ctx context.Context, conn *Conn, locale *Locale) *contactForm {
	return &contactForm{
		locale: locale,
		BusinessName: &InputField{
			Name:     "business_name",
			Label:    pgettext("input", "Business name", locale),
			Type:     "text",
			Required: true,
			Attributes: []template.HTMLAttr{
				`autocomplete="organization"`,
				`minlength="2"`,
			},
		},
		VATIN: &InputField{
			Name:     "vatin",
			Label:    pgettext("input", "VAT number", locale),
			Type:     "text",
			Required: true,
		},
		TradeName: &InputField{
			Name:  "trade_name",
			Label: pgettext("input", "Trade name", locale),
			Type:  "text",
		},
		Phone: &InputField{
			Name:     "phone",
			Label:    pgettext("input", "Phone", locale),
			Type:     "tel",
			Required: true,
			Attributes: []template.HTMLAttr{
				`autocomplete="tel"`,
			},
		},
		Email: &InputField{
			Name:     "email",
			Label:    pgettext("input", "Email", locale),
			Type:     "email",
			Required: true,
			Attributes: []template.HTMLAttr{
				`autocomplete="email"`,
			},
		},
		Web: &InputField{
			Name:  "web",
			Label: pgettext("input", "Web", locale),
			Type:  "url",
			Attributes: []template.HTMLAttr{
				`autocomplete="url"`,
			},
		},
		Address: &InputField{
			Name:     "address",
			Label:    pgettext("input", "Address", locale),
			Type:     "text",
			Required: true,
			Attributes: []template.HTMLAttr{
				`autocomplete="address-line1"`,
			},
		},
		City: &InputField{
			Name:     "city",
			Label:    pgettext("input", "City", locale),
			Type:     "text",
			Required: true,
		},
		Province: &InputField{
			Name:     "province",
			Label:    pgettext("input", "Province", locale),
			Type:     "text",
			Required: true,
		},
		PostalCode: &InputField{
			Name:     "postal_code",
			Label:    pgettext("input", "Postal code", locale),
			Type:     "text",
			Required: true,
			Attributes: []template.HTMLAttr{
				`autocomplete="postal-code"`,
			},
		},
		Country: &SelectField{
			Name:     "country",
			Label:    pgettext("input", "Country", locale),
			Options:  mustGetCountryOptions(ctx, conn, locale),
			Required: true,
			Selected: []string{"ES"},
			Attributes: []template.HTMLAttr{
				`autocomplete="country"`,
			},
		},
		Tags: &TagsField{
			Name:  "tags",
			Label: pgettext("input", "Tags", locale),
		},
	}
}

func (form *contactForm) Parse(r *http.Request) error {
	if err := r.ParseForm(); err != nil {
		return err
	}
	form.BusinessName.FillValue(r)
	form.VATIN.FillValue(r)
	form.TradeName.FillValue(r)
	form.Phone.FillValue(r)
	form.Email.FillValue(r)
	form.Web.FillValue(r)
	form.Address.FillValue(r)
	form.City.FillValue(r)
	form.Province.FillValue(r)
	form.PostalCode.FillValue(r)
	form.Country.FillValue(r)
	form.Tags.FillValue(r)
	return nil
}

func (form *contactForm) Validate(ctx context.Context, conn *Conn) bool {
	validator := newFormValidator()

	country := ""
	if validator.CheckValidSelectOption(form.Country, gettext("Selected country is not valid.", form.locale)) {
		country = form.Country.Selected[0]
	}

	validator.CheckRequiredInput(form.BusinessName, gettext("Business name can not be empty.", form.locale))
	validator.CheckInputMinLength(form.BusinessName, 2, gettext("Business name must have at least two letters.", form.locale))
	if validator.CheckRequiredInput(form.VATIN, gettext("VAT number can not be empty.", form.locale)) {
		validator.CheckValidVATINInput(form.VATIN, country, gettext("This value is not a valid VAT number.", form.locale))
	}
	if validator.CheckRequiredInput(form.Phone, gettext("Phone can not be empty.", form.locale)) {
		validator.CheckValidPhoneInput(form.Phone, country, gettext("This value is not a valid phone number.", form.locale))
	}
	if validator.CheckRequiredInput(form.Email, gettext("Email can not be empty.", form.locale)) {
		validator.CheckValidEmailInput(form.Email, gettext("This value is not a valid email. It should be like name@domain.com.", form.locale))
	}
	if form.Web.Val != "" {
		validator.CheckValidURL(form.Web, gettext("This value is not a valid web address. It should be like https://domain.com/.", form.locale))
	}
	validator.CheckRequiredInput(form.Address, gettext("Address can not be empty.", form.locale))
	validator.CheckRequiredInput(form.City, gettext("City can not be empty.", form.locale))
	validator.CheckRequiredInput(form.Province, gettext("Province can not be empty.", form.locale))
	if validator.CheckRequiredInput(form.PostalCode, gettext("Postal code can not be empty.", form.locale)) {
		validator.CheckValidPostalCode(ctx, conn, form.PostalCode, country, gettext("This value is not a valid postal code.", form.locale))
	}
	return validator.AllOK()
}

func (form *contactForm) MustFillFromDatabase(ctx context.Context, conn *Conn, slug string) bool {
	return !notFoundErrorOrPanic(conn.QueryRow(ctx, `
		select business_name
		     , substr(vatin::text, 3)
		     , trade_name
		     , phone
		     , email
		     , web
		     , address
		     , city
		     , province
		     , postal_code
		     , country_code
		     , array_to_string(tags, ',')
		from contact
		where slug = $1
	`, slug).Scan(
		form.BusinessName,
		form.VATIN,
		form.TradeName,
		form.Phone,
		form.Email,
		form.Web,
		form.Address,
		form.City,
		form.Province,
		form.PostalCode,
		form.Country,
		form.Tags))
}

func ServeEditContactTags(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, "/contacts/"+slug+"/tags"), slug, locale)
	if notFoundErrorOrPanic(conn.QueryRow(r.Context(), `select array_to_string(tags, ',') from contact where slug = $1`, form.Slug).Scan(&form.Tags)) {
		http.NotFound(w, r)
		return
	}
	mustRenderStandaloneTemplate(w, r, "tags/edit.gohtml", form)
}

func HandleUpdateContactTags(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, "/contacts/"+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 contact set tags = $1 where slug = $2 returning slug", form.Tags, form.Slug) == "" {
		http.NotFound(w, r)
	}
	mustRenderStandaloneTemplate(w, r, "tags/view.gohtml", form)
}
