package api

import (
	"context"
	"crud/sqlite"
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"strconv"
)

const baseQuery = `SELECT u.id, u.name, u.username,  u.email, u.phone, u.website, a.street, a.suite, a.zipcode, a.city, c.name as company, c.catch_phrase, c.bs 
				FROM user u
				JOIN company c ON u.company_id = c.id
				JOIN address a ON u.address_id = a.id 
				`

func Board(ctx context.Context, db *sqlite.Database, templ *template.Template) http.Handler {
	return http.HandlerFunc(

		func(w http.ResponseWriter, r *http.Request) {

			w.Header().Set("Content-Type", "text/html")

			records, err := sqlite.NoRowsOk(db.ReadRecords(ctx, baseQuery+";"))
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			// Execute template with proper error handling
			if err := templ.ExecuteTemplate(w, "board", sqlite.Record{"records": records}); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		},
	)
}

func DeleteRecord(ctx context.Context, db *sqlite.Database, templ *template.Template) http.Handler {
	// Implementation of DeleteRecord handler
	return http.HandlerFunc(

		func(w http.ResponseWriter, r *http.Request) {

			id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
			}

			// fmt.Println("DeleteRecord handler called ", id)

			if err := db.DeleteRecord(ctx, "user", "id", id); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			// Redirect or respond with success
			http.Redirect(w, r, "/board", http.StatusSeeOther)
		},
	)
}

func EditRecord(ctx context.Context, db *sqlite.Database, templ *template.Template) http.Handler {
	// Implementation of EditRecord handler
	return http.HandlerFunc(

		func(w http.ResponseWriter, r *http.Request) {

			// fmt.Println("EditRecord handler called")

			id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
			}

			records, err := db.ReadRecords(ctx, baseQuery+" WHERE u.id = ?;", id)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			rec := records[0]

			// fmt.Printf("Record to edit: %+v\n", rec)

			w.Header().Set("Content-Type", "text/html")

			// Execute template with proper error handling
			if err := templ.ExecuteTemplate(w, "edit-user", rec); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

		},
	)
}

func PatchRecord(ctx context.Context, db *sqlite.Database, templ *template.Template) http.Handler {
	// Implementation of PatchRecord handler
	return http.HandlerFunc(

		func(w http.ResponseWriter, r *http.Request) {

			fmt.Println("PatchRecord handler called")

			// id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
			// if err != nil {
			// 	w.WriteHeader(http.StatusInternalServerError)
			// 	w.Write([]byte(err.Error()))
			// }

			// if err := db.DeleteRecord(ctx, "user", "id", id); err != nil {
			// 	http.Error(w, err.Error(), http.StatusInternalServerError)
			// 	return
			// }

			// Redirect or respond with success
			http.Redirect(w, r, "/board", http.StatusSeeOther)

		},
	)
}

func RecordJson(ctx context.Context, db *sqlite.Database, templ *template.Template) http.Handler {
	// Implementation of EditRecord handler
	return http.HandlerFunc(

		func(w http.ResponseWriter, r *http.Request) {

			id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
			}

			records, err := db.ReadRecords(ctx, baseQuery+" WHERE u.id = ?;", id)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			rec := records[0]

			w.Header().Set("Content-Type", "application/json")

			if err := json.NewEncoder(w).Encode(rec); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

		},
	)
}
