package handlers

import (
	"fikoyt-ajan/internal/notification"
	"fmt"
	"log"
	"sync"
	"time"
)

// MesajHandler - Mesaj işleyici
type MesajHandler struct {
	// Notification manager referansı
	notificationManager *notification.Manager

	// Aktif progress bildirimleri
	progressMap sync.Map
}

// ProgressInfo - Progress bildirim bilgisi
type ProgressInfo struct {
	ID        string
	Baslik    string
	Aciklama  string
	Deger     float64 // 0.0 - 1.0
	Durum     string  // "devam", "tamamlandi", "hata"
	StopChan  chan bool
	UpdatedAt time.Time
}

// YeniMesajHandler - Yeni mesaj handler
func YeniMesajHandler(nm *notification.Manager) *MesajHandler {
	return &MesajHandler{
		notificationManager: nm,
	}
}

// CevapCallback - Cevap gönderme fonksiyonu
type CevapCallback func(mesajId string, cevap string)

// MesajIsle - Gelen mesajı işle
func (mh *MesajHandler) MesajIsle(data map[string]interface{}, cevapGonder CevapCallback) {
	mesajId, _ := data["mesajId"].(string)
	tip, _ := data["tip"].(string)
	baslik, _ := data["baslik"].(string)

	log.Printf("Mesaj işleniyor - Tip: %s, Başlık: %s", tip, baslik)

	switch tip {
	case "toast":
		mh.toastGoster(data)
		if cevapGonder != nil && mesajId != "" {
			cevapGonder(mesajId, "okundu")
		}
	case "dialog":
		mh.DialogIsle(data, cevapGonder)
	case "progress":
		mh.ProgressIsle(data, cevapGonder)
	case "progress_guncelle":
		mh.ProgressGuncelle(data)
	case "progress_kapat":
		mh.ProgressKapat(data)
	default:
		// Varsayılan toast
		mh.toastGoster(data)
	}
}

// toastGoster - Toast bildirimi göster (Wails notification manager kullanarak)
func (mh *MesajHandler) toastGoster(data map[string]interface{}) {
	if mh.notificationManager == nil {
		log.Println("Notification manager nil, bildirim gösterilemedi")
		return
	}

	// Notification manager'a gönder
	mh.notificationManager.ShowFromData(data)
}

// DialogIsle - Dialog mesajını işle
func (mh *MesajHandler) DialogIsle(data map[string]interface{}, cevapGonder CevapCallback) {
	mesajId, _ := data["mesajId"].(string)
	baslik, _ := data["baslik"].(string)
	icerik, _ := data["icerik"].(string)
	butonlar, _ := data["butonlar"].([]interface{})

	log.Printf("Dialog gösteriliyor - Başlık: %s", baslik)

	// Butonları string'e çevir - hem string[] hem de [{text, renk, ikon}] formatını destekle
	butonStrs := []string{}
	for _, b := range butonlar {
		switch v := b.(type) {
		case string:
			// Eski format: string dizisi
			butonStrs = append(butonStrs, v)
		case map[string]interface{}:
			// Yeni format: {text, renk, ikon} nesneleri
			if text, ok := v["text"].(string); ok && text != "" {
				butonStrs = append(butonStrs, text)
			}
		}
	}

	if len(butonStrs) == 0 {
		butonStrs = []string{"Tamam"}
	}

	// Notification manager ile dialog göster
	if mh.notificationManager != nil {
		mh.notificationManager.ShowDialog(baslik, icerik, butonStrs, func(buttonId string, buttonLabel string) {
			if cevapGonder != nil && mesajId != "" {
				cevapGonder(mesajId, buttonLabel)
			}
		})
	}
}

// ProgressIsle - Progress bildirimini başlat
func (mh *MesajHandler) ProgressIsle(data map[string]interface{}, cevapGonder CevapCallback) {
	progressId, _ := data["progressId"].(string)
	baslik, _ := data["baslik"].(string)
	aciklama, _ := data["aciklama"].(string)
	deger, _ := data["deger"].(float64)

	if progressId == "" {
		progressId = fmt.Sprintf("progress_%d", time.Now().UnixNano())
	}

	log.Printf("Progress başlatılıyor - ID: %s, Başlık: %s", progressId, baslik)

	// Progress bilgisini kaydet
	info := &ProgressInfo{
		ID:        progressId,
		Baslik:    baslik,
		Aciklama:  aciklama,
		Deger:     deger,
		Durum:     "devam",
		StopChan:  make(chan bool),
		UpdatedAt: time.Now(),
	}
	mh.progressMap.Store(progressId, info)

	// Notification manager ile progress göster
	if mh.notificationManager != nil {
		notifId := mh.notificationManager.ShowProgress(baslik, aciklama, deger)
		// Notification ID'yi progress ID ile eşleştir
		info.ID = notifId
		mh.progressMap.Store(progressId, info)
	}

	// Cevap gönder
	if cevapGonder != nil {
		cevapGonder(progressId, "baslatildi")
	}
}

// ProgressGuncelle - Progress bildirimini güncelle
func (mh *MesajHandler) ProgressGuncelle(data map[string]interface{}) {
	progressId, _ := data["progressId"].(string)
	aciklama, _ := data["aciklama"].(string)
	deger, _ := data["deger"].(float64)

	if val, ok := mh.progressMap.Load(progressId); ok {
		info := val.(*ProgressInfo)
		if aciklama != "" {
			info.Aciklama = aciklama
		}
		info.Deger = deger
		info.UpdatedAt = time.Now()

		log.Printf("Progress güncelleniyor - ID: %s, Değer: %.0f%%", progressId, deger*100)

		// Notification manager ile güncelle
		if mh.notificationManager != nil {
			mh.notificationManager.UpdateProgress(info.ID, deger, aciklama)
		}
	}
}

// ProgressKapat - Progress bildirimini kapat
func (mh *MesajHandler) ProgressKapat(data map[string]interface{}) {
	progressId, _ := data["progressId"].(string)
	durum, _ := data["durum"].(string) // "tamamlandi" veya "hata"
	mesaj, _ := data["mesaj"].(string)

	if val, ok := mh.progressMap.Load(progressId); ok {
		info := val.(*ProgressInfo)
		info.Durum = durum
		close(info.StopChan)
		mh.progressMap.Delete(progressId)

		log.Printf("Progress kapatılıyor - ID: %s, Durum: %s", progressId, durum)

		// Notification manager ile tamamla
		if mh.notificationManager != nil {
			success := durum == "tamamlandi"
			mh.notificationManager.CompleteProgress(info.ID, mesaj, success)
		}
	}
}
