package tui

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type ChatMessage struct {
	ID        string `json:"id"`
	Sender    string `json:"sender"`
	Receiver  string `json:"receiver"`
	Content   string `json:"content"`
	Timestamp string `json:"timestamp"`
}

type ChatData struct {
	Messages []ChatMessage `json:"messages"`
}

func LoadContacts(path string) {
	users = nil
	contactsPath := filepath.Join(path, "users")
	folders, err := os.ReadDir(contactsPath)
	if err != nil {
		log.Printf("Error reading contacts directory: %v", err)
		return
	}

	// TODO: Instead of just using list create some more complex structure so i can load details about the user in it
	for _, folder := range folders {
		if folder.IsDir() {
			users = append(users, folder.Name())
		}
	}
}

func WriteMessage(username, sender, receiver, content string) error {
	chatFile := filepath.Join("configs", "servers", "default", "users", strings.ToLower(username), "messages.json")

	if _, err := os.Stat(chatFile); os.IsNotExist(err) {
		emptyData := ChatData{Messages: []ChatMessage{}}
		data, _ := json.MarshalIndent(emptyData, "", "    ")
		if err := os.WriteFile(chatFile, data, 0644); err != nil {
			return fmt.Errorf("failed to create chat file: %v", err)
		}
	}

	data, err := os.ReadFile(chatFile)
	if err != nil {
		return fmt.Errorf("error reading chat file: %v", err)
	}

	var chatData ChatData
	if len(data) > 0 {
		if err := json.Unmarshal(data, &chatData); err != nil {
			return fmt.Errorf("error parsing JSON: %v", err)
		}
	}

	newID := "1"
	if len(chatData.Messages) > 0 {
		lastMsg := chatData.Messages[len(chatData.Messages)-1]
		if lastID, err := strconv.Atoi(lastMsg.ID); err == nil {
			newID = strconv.Itoa(lastID + 1)
		}
	}

	encodedContent := base64.StdEncoding.EncodeToString([]byte(content))

	newMsg := ChatMessage{
		ID:        newID,
		Sender:    sender,
		Receiver:  receiver,
		Content:   encodedContent,
		Timestamp: time.Now().UTC().Format(time.RFC3339),
	}

	chatData.Messages = append(chatData.Messages, newMsg)
	updatedData, err := json.MarshalIndent(chatData, "", "    ")
	if err != nil {
		return fmt.Errorf("error encoding JSON: %v", err)
	}

	if err := os.WriteFile(chatFile, updatedData, 0644); err != nil {
		return fmt.Errorf("error writing chat file: %v", err)
	}

	return nil
}

func LoadMessages(username string) {
	chatFile := filepath.Join("configs", "servers", "default", "users", strings.ToLower(username), "messages.json")
	data, err := os.ReadFile(chatFile)
	if err != nil {
		log.Printf("Error reading chat file: %v", err)
		return
	}

	if err := json.Unmarshal(data, &chatData); err != nil {
		log.Printf("Error parsing JSON: %v", err)
		return
	}
}
