// src/pages/DeckCreator/DeckCreator.jsx
// Deck Creator Page - Deck létrehozás és szerkesztés

import React, { useState, useEffect } from "react"
import { useParams, useNavigate } from "react-router-dom"
import Navbar from "../../components/Navbar/Navbar.jsx"
import DeckHeader from "../../components/DeckCreator/DeckHeader.jsx"
import CardsList from "../../components/DeckCreator/CardsList.jsx"
import CardEditor from "../../components/DeckCreator/CardEditor.jsx"
import { createDeck } from '../../api/deckApi'
import { notifySuccess, notifyError, notifyWarning } from "../../components/Toastify/toastifyServices"

export default function DeckCreator() {
  const { deckId } = useParams() // URL-ből deck ID (új deck esetén undefined)
  const navigate = useNavigate()

  // Deck alapadatok
  const [deck, setDeck] = useState({
    id: null,
    name: "Új Pakli",
    type: "QUESTION", // QUESTION, LUCK, JOKER - backend formátum
    privacy: "private", // private, public
    description: "",
    cards: []
  })

  // UI állapotok
  const [selectedCard, setSelectedCard] = useState(null)
  const [isCreatingCard, setIsCreatingCard] = useState(false)
  const [newCardType, setNewCardType] = useState(null)

  // Betöltés API-ból
  useEffect(() => {
    if (deckId) {
      loadDeck(deckId)
    } else {
      setDeck({
        id: null,
        name: "Új Pakli",
        type: "QUESTION",
        privacy: "private",
        description: "",
        cards: []
      })
    }
  }, [deckId])

  const handleDeckUpdate = (updates) => {
    setDeck(prev => ({ ...prev, ...updates }))
  }

  const handleSaveDeck = async () => {
    try {
      const payload = {
        name: deck.name,
        type: deck.type,
        ctype: deck.privacy === 'public' ? 'PUBLIC' : 'PRIVATE',
        description: deck.description || '',
        cards: deck.cards
      }

      const saved = await createDeck(payload)
      setDeck(prev => ({
        ...prev,
        id: saved.id ?? prev.id,
        creationdate: saved.creationdate ?? prev.creationdate,
        updatedate: saved.updatedate ?? prev.updatedate
      }))

      console.log('Deck saved (backend):', saved)
      notifySuccess('Deck sikeresen mentve!')
    } catch (error) {
      console.error('Mentési hiba:', error)
      notifyError('Hiba történt a mentés során: ' + (error?.response?.data?.error || error.message || String(error)))
    }
  }

  // 🔧 Itt korábban volt confirm(), de most eltávolítottuk
  const handleBack = () => {
    // Egyszerű visszalépés — ha akarsz, később adhatunk hozzá saját modalt
    navigate("/decks")
  }

  const handleCreateCard = (cardType) => {
    setNewCardType(cardType)
    setIsCreatingCard(true)
    setSelectedCard(null)
  }

  const handleSelectCard = (card) => {
    setSelectedCard(card)
    setIsCreatingCard(false)
    setNewCardType(null)
  }

  const handleSaveCard = (cardData) => {
    try {
      const updatedCard = {
        ...cardData,
        id: isCreatingCard ? Date.now() : cardData.id
      }
      
      setDeck(prev => {
        // Ellenőrizzük, vannak-e nem megfelelő típusú kártyák
        const invalidCards = prev.cards.filter(card => card.type !== prev.type)
        
        // Ha új kártyát mentünk megfelelő típussal és vannak nem megfelelők
        if (isCreatingCard && cardData.type === prev.type && invalidCards.length > 0) {
          notifyWarning(`${invalidCards.length} db nem megfelelő típusú kártya törlésre került`)
          
          return {
            ...prev,
            cards: [
              ...prev.cards.filter(card => card.type === prev.type),
              updatedCard
            ]
          }
        }
        
        // Alap mentési logika
        return {
          ...prev,
          cards: isCreatingCard 
            ? [...prev.cards, updatedCard]
            : prev.cards.map(card => card.id === updatedCard.id ? updatedCard : card)
        }
      })

      setSelectedCard(updatedCard)
      setIsCreatingCard(false)
      setNewCardType(null)
      
      notifySuccess('Kártya sikeresen mentve!')
    } catch (error) {
      console.error('Kártya mentési hiba:', error)
      notifyError('Hiba történt a kártya mentése során')
    }
  }

  // 🔧 Itt is confirm() volt — most a CardsList popupja kezeli a megerősítést
  const handleDeleteCard = (cardId) => {
    setDeck(prev => ({
      ...prev,
      cards: prev.cards.filter(card => card.id !== cardId)
    }))

    if (selectedCard?.id === cardId) {
      setSelectedCard(null)
    }
  }

  return (
    <div className="w-full min-h-screen bg-[color:var(--color-background)] flex flex-col">
      <Navbar />

      <main className="flex-1 flex flex-col">
        {/* Deck Header */}
        <DeckHeader
          deck={deck}
          onUpdate={handleDeckUpdate}
          onSave={handleSaveDeck}
          onBack={handleBack}
        />

        {/* Main Content */}
        <div className="flex-1 flex">
          {/* Left Panel - Cards List */}
          <div className="w-80 bg-[color:var(--color-surface)] border-r border-[color:var(--color-surface-selected)] flex flex-col">
            <CardsList
              cards={deck.cards}
              selectedCard={selectedCard}
              deckType={deck.type}
              onSelectCard={handleSelectCard}
              onCreateCard={handleCreateCard}
              onDeleteCard={handleDeleteCard}
              isCreatingCard={isCreatingCard}
              newCardType={newCardType}
            />
          </div>

          {/* Right Panel - Card Editor */}
          <div className="flex-1 bg-[color:var(--color-background)] flex flex-col">
            <CardEditor
              card={selectedCard}
              isCreating={isCreatingCard}
              cardType={isCreatingCard ? newCardType : deck.type}
              onSave={handleSaveCard}
              onCancel={() => {
                setIsCreatingCard(false)
                setNewCardType(null)
                setSelectedCard(null)
              }}
            />
          </div>
        </div>
      </main>
    </div>
  )
}
