import { useState, useEffect } from 'react';
import { useRouter } from 'next/router';

const EMPTY_NEW_DECK = {
  name: '',
  description: '',
  format: 'Commander',
  is_public: false,
};

/**
 * Decks list page state and handlers (god-component split).
 */
export function useDecksPage({ user = null, authLoading = true } = {}) {
  const router = useRouter();
  const [decks, setDecks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingDeck, setEditingDeck] = useState(null);
  const [newDeck, setNewDeck] = useState(EMPTY_NEW_DECK);

  const fetchDecks = async () => {
    try {
      const token = localStorage.getItem('auth_token');
      const response = await fetch('/api/decks', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const data = await response.json();
        setDecks(data);
      } else {
        console.error('Failed to fetch decks');
      }
    } catch (error) {
      console.error('Error fetching decks:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (user) {
      // eslint-disable-next-line react-hooks/set-state-in-effect -- load decks when user is available
      fetchDecks();
    }
  }, [user]);

  const handleCreateDeck = async (e) => {
    e.preventDefault();
    try {
      const token = localStorage.getItem('auth_token');
      const response = await fetch('/api/decks', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(newDeck),
      });

      if (response.ok) {
        const createdDeck = await response.json();
        setDecks([createdDeck, ...decks]);
        setShowCreateModal(false);
        setNewDeck(EMPTY_NEW_DECK);
        router.push(`/deck-builder?deck=${createdDeck.id}`);
      } else {
        console.error('Failed to create deck');
      }
    } catch (error) {
      console.error('Error creating deck:', error);
    }
  };

  const handleEditDeck = async (e) => {
    e.preventDefault();
    try {
      const token = localStorage.getItem('auth_token');
      const response = await fetch(`/api/decks/${editingDeck.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(editingDeck),
      });

      if (response.ok) {
        const updatedDeck = await response.json();
        setDecks(decks.map((deck) => (deck.id === updatedDeck.id ? updatedDeck : deck)));
        setEditingDeck(null);
      } else {
        console.error('Failed to update deck');
      }
    } catch (error) {
      console.error('Error updating deck:', error);
    }
  };

  const handleDeleteDeck = async (deckId) => {
    if (!confirm('Are you sure you want to delete this deck? This action cannot be undone.')) {
      return;
    }
    try {
      const token = localStorage.getItem('auth_token');
      const response = await fetch(`/api/decks/${deckId}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` },
      });

      if (response.ok) {
        setDecks(decks.filter((deck) => deck.id !== deckId));
      } else {
        console.error('Failed to delete deck');
      }
    } catch (error) {
      console.error('Error deleting deck:', error);
    }
  };

  const showLoggedOut = !authLoading && !user;
  const showInitialLoading = Boolean(user) && loading;

  return {
    authLoading,
    decks,
    editingDeck,
    handleCreateDeck,
    handleDeleteDeck,
    handleEditDeck,
    newDeck,
    setEditingDeck,
    setNewDeck,
    setShowCreateModal,
    showCreateModal,
    showInitialLoading,
    showLoggedOut,
    user,
  };
}
