package controllers

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gitlab.com/pactual1/backend/database/invoice"
	"gitlab.com/pactual1/backend/models"
)

func GetInvoices(c *gin.Context) {
	limitStr := c.DefaultQuery("limit", "10")
	offsetStr := c.DefaultQuery("offset", "0")
	buyerName := c.Query("buyer_name")
	sortBy := c.Query("sort_by")
	iDsStr := c.QueryArray("ids[]")
	status := c.QueryArray("status")
	companyID := c.GetInt("companyID")

	limit, err := strconv.Atoi(limitStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid limit value"})
		return
	}

	offset, err := strconv.Atoi(offsetStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid offset value"})
		return
	}

	// Convert ids to []int64
	var invoiceIDs []int64
	for _, idStr := range iDsStr {
		id, err := strconv.ParseInt(idStr, 10, 64)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid id value"})
			return
		}
		invoiceIDs = append(invoiceIDs, id)
	}

	invoices, total, err := invoice.GetInvoices(buyerName, sortBy, limit, offset, invoiceIDs, status, companyID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// Convert to ListInvoiceResponse type
	listInvoiceResponses := convertToResponseModel(invoices)

	c.JSON(http.StatusOK, gin.H{"total": total, "data": listInvoiceResponses})
}

func GetInvoiceByID(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"})
		return
	}

	companyID := c.GetInt("companyID")

	invoices, _, err := invoice.GetInvoices("", "", 1, 0, []int64{int64(id)}, nil, companyID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	invoiceResponses := models.ConvertInvoiceToResponse(invoices)

	if len(invoices) > 0 {
		c.JSON(http.StatusOK, gin.H{"data": invoiceResponses[0]})
	} else {
		c.JSON(http.StatusNotFound, gin.H{"error": "Invoice not found"})
	}
}

func convertToResponseModel(invoices []models.Invoice) []models.ListInvoiceResponse {
	listInvoiceResponses := []models.ListInvoiceResponse{}

	// Get all statuses
	statuses := models.GetInvoiceStatuses()
	statusMap := make(map[string]models.Status)
	for _, s := range statuses {
		statusMap[s.Value] = s
	}

	for _, invoice := range invoices {
		// Get the status based on Value in the DB
		status, ok := statusMap[invoice.Status]
		if !ok {
			status = models.Status{Key: "Unknown", Value: "unknown"}
		}

		listInvoiceResponse := models.ListInvoiceResponse{
			Status:      models.KeyValue{Key: status.Key, Value: status.Value},
			Buyer:       models.CompanyShortResponse{ID: int(invoice.BuyerID), Name: invoice.BuyerName},
			ContractID:  int(invoice.ContractID),
			DateCreated: invoice.InvoiceDate,
			DueDate:     invoice.InvoiceDueDate,
			Amount:      strconv.FormatInt(invoice.PriceCents, 10),
		}
		listInvoiceResponses = append(listInvoiceResponses, listInvoiceResponse)
	}
	return listInvoiceResponses
}

func GetInvoiceCountByStatus(c *gin.Context) {
	companyID := c.DefaultQuery("company_id", "0")
	startTimeStr := c.DefaultQuery("start_time", "")
	endTimeStr := c.DefaultQuery("end_time", "")

	// Convert to uint and time.Time
	companyIDUint, err := strconv.ParseUint(companyID, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "Invalid companyID",
		})
		return
	}

	// Convert string to Unix timestamp
	startUnix, _ := strconv.ParseInt(startTimeStr, 10, 64)
	endUnix, _ := strconv.ParseInt(endTimeStr, 10, 64)

	// Convert Unix timestamps to time.Time
	startTime := time.Unix(startUnix, 0)
	endTime := time.Unix(endUnix, 0)

	activeCount, executedCount, monthly, err := invoice.CountInvoicesByMultipleStatuses(uint(companyIDUint), startTime, endTime)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Internal Server Error",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": models.ActiveInvoiceResponse{Claimed: activeCount, Issued: executedCount, MonthlyInvoices: monthly}})

}
