// 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'

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 Deck",
    type: "Question", // Question, Luck, Fun
    privacy: "private", // private, public
    description: "",
    cards: []
  })

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

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

  const loadDeck = async (id) => {
    // Mock deck betöltés
    const mockDeck = {
      id: id,
      name: "Quiz Night",
      type: "Question",
      privacy: "public",
      description: "Szórakoztató kvíz este",
      cards: [
        {
          id: 1,
          type: "task",
          subType: "quiz",
          question: "Mi Magyarország fővárosa?",
          options: ["Budapest", "Debrecen", "Szeged", "Pécs"],
          correctAnswer: 0,
          points: 10,
          timeLimit: 30,
          explanation: "Budapest 1873 óta Magyarország fővárosa."
        },
        {
          id: 2,
          type: "task",
          subType: "truefalse",
          statement: "A Duna Magyarország leghosszabb folyója.",
          isTrue: false,
          points: 5,
          timeLimit: 15,
          explanation: "A Tisza a leghosszabb folyó Magyarországon."
        }
      ]
    }
    setDeck(mockDeck)
  }

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

  const handleSaveDeck = async () => {
    try {
      console.log("Deck mentése:", deck)

      const payload = {
        name: deck.name,
        type: (deck.type || 'Question').toString().toUpperCase(),
        ctype: deck.privacy === 'public' ? 'PUBLIC' : 'PRIVATE',
        description: deck.description || '',
        cards: deck.cards.map(c => ({ ...c, text: c.question || c.statement || c.text || '' }))
      }

      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)
      alert('✅ Deck sikeresen mentve!')
    } catch (error) {
      console.error('Mentési hiba:', error)
      alert('❌ Hiba történt a mentés során: ' + (error?.response?.data?.error || error.message || String(error)))
    }
  }

  const handleBack = () => {
    if (confirm("Biztosan visszamész? A nem mentett változtatások elvesznek.")) {
      navigate("/decks")
    }
  }

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

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

  const handleSaveCard = (cardData) => {
    if (isCreatingCard) {
      // Új kártya hozzáadása
      const newCard = {
        ...cardData,
        id: Date.now(), // Temporary ID
      }
      setDeck(prev => ({
        ...prev,
        cards: [...prev.cards, newCard]
      }))
      setIsCreatingCard(false)
      setNewCardType(null)
      setSelectedCard(newCard)
    } else {
      // Meglévő kártya frissítése
      setDeck(prev => ({
        ...prev,
        cards: prev.cards.map(card => 
          card.id === cardData.id ? cardData : card
        )
      }))
      setSelectedCard(cardData)
    }
  }

  const handleDeleteCard = (cardId) => {
    if (confirm("Biztosan törlöd ezt a kártyát?")) {
      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}
              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={newCardType}
              onSave={handleSaveCard}
              onCancel={() => {
                setIsCreatingCard(false)
                setNewCardType(null)
                setSelectedCard(null)
              }}
            />
          </div>
        </div>
      </main>
    </div>
  )
}