package exports

import (
	"context"
	"fmt"
	"net/http"

	"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
	fleets "git.coopgo.io/coopgo-platform/fleets/grpcapi"
	fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
	groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
	groupsstorage "git.coopgo.io/coopgo-platform/groups-management/storage"
	accounts "git.coopgo.io/coopgo-platform/mobility-accounts/grpcapi"
	accountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
	"github.com/xuri/excelize/v2"
)

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

	vehicles := map[string]fleetsstorage.Vehicle{}
	bookings := []fleetsstorage.Booking{}
	reequest := &fleets.GetVehiclesRequest{
		Namespaces: []string{"parcoursmob"},
	}
	reesp, err := h.services.GRPC.Fleets.GetVehicles(context.TODO(), reequest)
	if err != nil {
		fmt.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	beneficiaries_ids := []string{}

	for _, vehicle := range reesp.Vehicles {

		v := vehicle.ToStorageType()
		fmt.Println(v)

		for _, b := range v.Bookings {
			bookings = append(bookings, b)
			beneficiaries_ids = append(beneficiaries_ids, b.Driver)
		}

		vehicles[vehicle.Id] = v

	}


	groups := map[string]groupsstorage.Group{}

	admingroups, err := h.services.GRPC.GroupsManagement.GetGroups(context.TODO(), &groupsmanagement.GetGroupsRequest{
		Namespaces: []string{"parcoursmob_organizations"},
	})
	if err != nil {
		fmt.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	for _, g := range admingroups.Groups {
		groups[g.Id] = g.ToStorageType()
	}

	beneficiaries, err := h.services.GRPC.MobilityAccounts.GetAccountsBatch(context.TODO(), &accounts.GetAccountsBatchRequest{
		Accountids: beneficiaries_ids,
	})
	if err != nil {
		fmt.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	beneficiaries_map := map[string]accountsstorage.Account{}
	for _, ben := range beneficiaries.Accounts {
		beneficiaries_map[ben.Id] = ben.ToStorageType()
	}

	/////////////// Generate file

	f := excelize.NewFile()
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()

	f.SetCellValue("Sheet1", "A1", "Numéro")
	f.SetCellValue("Sheet1", "B1", "Type")
	f.SetCellValue("Sheet1", "C1", "Gestionnaire")
	f.SetCellValue("Sheet1", "D1", "Prescripteur")
	f.SetCellValue("Sheet1", "E1", "Bénéficiaire")
	f.SetCellValue("Sheet1", "F1", "Numéro allocataire / Pole emploi")
	f.SetCellValue("Sheet1", "G1", "Début de Mise à disposition")
	f.SetCellValue("Sheet1", "H1", "Fin de mise à disposition")
	f.SetCellValue("Sheet1", "I1", "Début indisponibilité")
	f.SetCellValue("Sheet1", "J1", "Fin indisponibilité")
	f.SetCellValue("Sheet1", "K1", "Retrait par le gestionnaire")
	f.SetCellValue("Sheet1", "L1", "Commentaire")

	i := 2
	for _, b := range bookings {
		vehicle := vehicles[b.Vehicleid]
		if len(vehicle.Administrators) == 0 {
			continue
		}
		admin := groups[vehicle.Administrators[0]]

		bookedby := ""
		if v, ok := b.Data["booked_by"].(map[string]any); ok {
			if v2, ok := v["user"].(map[string]any); ok {
				if v3, ok := v2["display_name"].(string); ok {
					bookedby = v3
				}

			}
		}

		bookedbygroup := ""
		if v4, ok := b.Data["booked_by"].(map[string]any); ok {
			if v5, ok := v4["group"].(map[string]any); ok {
				if v6, ok := v5["id"].(string); ok {
					bookedbygroup = v6
				}
			}
		}

		// filter by group
		g := r.Context().Value(identification.GroupKey)
		group := g.(groupsstorage.Group)
		
		if bookedbygroup != group.ID {
			continue
		}

		beneficiary := beneficiaries_map[b.Driver]
		adminunavailability := false

		if av, ok := b.Data["administrator_unavailability"].(bool); ok && av {
			adminunavailability = true
		}

		f.SetCellValue("Sheet1", fmt.Sprintf("A%d", i), vehicle.Data["licence_plate"])
		f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i), vehicle.Type)
		f.SetCellValue("Sheet1", fmt.Sprintf("C%d", i), admin.Data["name"])
		f.SetCellValue("Sheet1", fmt.Sprintf("D%d", i), bookedby)
		f.SetCellValue("Sheet1", fmt.Sprintf("E%d", i), fmt.Sprintf("%v %v", beneficiary.Data["first_name"], beneficiary.Data["last_name"]))
		f.SetCellValue("Sheet1", fmt.Sprintf("F%d", i), beneficiary.Data["file_number"])
		f.SetCellValue("Sheet1", fmt.Sprintf("G%d", i), b.Startdate.Format("2006-01-02"))
		f.SetCellValue("Sheet1", fmt.Sprintf("H%d", i), b.Enddate.Format("2006-01-02"))
		f.SetCellValue("Sheet1", fmt.Sprintf("I%d", i), b.Unavailablefrom.Format("2006-01-02"))
		f.SetCellValue("Sheet1", fmt.Sprintf("J%d", i), b.Unavailableto.Format("2006-01-02"))
		f.SetCellValue("Sheet1", fmt.Sprintf("K%d", i), adminunavailability)
		f.SetCellValue("Sheet1", fmt.Sprintf("L%d", i), b.Data["comment"])
		i = i + 1
	}

	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
	w.Header().Set("Content-Transfer-Encoding", "binary")
	w.Header().Set("Expires", "0")
	f.Write(w)

}
