'use client';

import { useEffect, useState } from 'react';
import AudioPlayer from './AudioPlayer';
import GuessInput from './GuessInput';
import Statistics from './Statistics';
import { useGameState } from '../lib/gameState';
import { sendGotifyNotification } from '../app/actions';

interface GameProps {
    dailyPuzzle: {
        id: number;
        puzzleNumber: number;
        audioUrl: string;
        songId: number;
        title: string;
        artist: string;
        coverImage: string | null;
        startTime?: number;
    } | null;
    genre?: string | null;
    isSpecial?: boolean;
    maxAttempts?: number;
    unlockSteps?: number[];
}

const DEFAULT_UNLOCK_STEPS = [2, 4, 7, 11, 16, 30, 60];

export default function Game({ dailyPuzzle, genre = null, isSpecial = false, maxAttempts = 7, unlockSteps = DEFAULT_UNLOCK_STEPS }: GameProps) {
    const { gameState, statistics, addGuess } = useGameState(genre, maxAttempts);
    const [hasWon, setHasWon] = useState(false);
    const [hasLost, setHasLost] = useState(false);
    const [shareText, setShareText] = useState('🔗 Share');
    const [lastAction, setLastAction] = useState<'GUESS' | 'SKIP' | null>(null);
    const [isProcessingGuess, setIsProcessingGuess] = useState(false);
    const [timeUntilNext, setTimeUntilNext] = useState('');

    useEffect(() => {
        const updateCountdown = () => {
            const now = new Date();
            const tomorrow = new Date(now);
            tomorrow.setHours(24, 0, 0, 0);
            const diff = tomorrow.getTime() - now.getTime();

            const hours = Math.floor(diff / (1000 * 60 * 60));
            const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

            setTimeUntilNext(`${hours}h ${minutes}m`);
        };

        updateCountdown();
        const interval = setInterval(updateCountdown, 1000); // Update every second to be accurate
        return () => clearInterval(interval);
    }, []);

    useEffect(() => {
        if (gameState && dailyPuzzle) {
            setHasWon(gameState.isSolved);
            setHasLost(gameState.isFailed);
        }
    }, [gameState, dailyPuzzle]);

    useEffect(() => {
        setLastAction(null);
    }, [dailyPuzzle?.id]);

    if (!dailyPuzzle) return (
        <div className="game-container" style={{ textAlign: 'center', padding: '2rem' }}>
            <h2>No Puzzle Available</h2>
            <p>Could not generate a daily puzzle.</p>
            <p>Please ensure there are songs in the database{genre ? ` for genre "${genre}"` : ''}.</p>
            <a href="/admin" style={{ color: 'var(--primary)', textDecoration: 'underline' }}>Go to Admin Dashboard</a>
        </div>
    );
    if (!gameState) return <div>Loading state...</div>;

    const handleGuess = (song: any) => {
        if (isProcessingGuess) return; // Prevent multiple guesses

        setIsProcessingGuess(true);
        setLastAction('GUESS');
        if (song.id === dailyPuzzle.songId) {
            addGuess(song.title, true);
            setHasWon(true);
            sendGotifyNotification(gameState.guesses.length + 1, 'won', dailyPuzzle.id, genre);
        } else {
            addGuess(song.title, false);
            if (gameState.guesses.length + 1 >= maxAttempts) {
                setHasLost(true);
                setHasWon(false); // Ensure won is false
                sendGotifyNotification(maxAttempts, 'lost', dailyPuzzle.id, genre);
            }
        }
        // Reset after a short delay to allow UI update
        setTimeout(() => setIsProcessingGuess(false), 500);
    };

    const handleSkip = () => {
        setLastAction('SKIP');
        addGuess("SKIPPED", false);
    };

    const handleGiveUp = () => {
        setLastAction('SKIP');
        addGuess("SKIPPED", false);
        setHasLost(true);
        setHasWon(false);
        sendGotifyNotification(maxAttempts, 'lost', dailyPuzzle.id, genre);
    };

    const unlockedSeconds = unlockSteps[Math.min(gameState.guesses.length, unlockSteps.length - 1)];

    const handleShare = async () => {
        let emojiGrid = '';
        const totalGuesses = maxAttempts;

        // Build the grid
        for (let i = 0; i < totalGuesses; i++) {
            if (i < gameState.guesses.length) {
                // If this was the winning guess (last one and won)
                if (hasWon && i === gameState.guesses.length - 1) {
                    emojiGrid += '🟩';
                } else {
                    // Wrong or skipped
                    emojiGrid += '⬛';
                }
            } else {
                // Unused attempts
                emojiGrid += '⬜';
            }
        }

        const speaker = hasWon ? '🔉' : '🔇';
        const genreText = genre ? `Genre: ${genre}\n` : '';

        // Generate URL with genre/special path
        let shareUrl = 'https://hoerdle.elpatron.me';
        if (genre) {
            if (isSpecial) {
                shareUrl += `/special/${encodeURIComponent(genre)}`;
            } else {
                shareUrl += `/${encodeURIComponent(genre)}`;
            }
        }

        const text = `Hördle #${dailyPuzzle.puzzleNumber}\n${genreText}\n${speaker}${emojiGrid}\n\n#Hördle #Music\n\n${shareUrl}`;

        // Try native Web Share API only on mobile devices
        const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

        if (isMobile && navigator.share) {
            try {
                await navigator.share({
                    title: `Hördle #${dailyPuzzle.puzzleNumber}`,
                    text: text,
                });
                setShareText('✓ Shared!');
                setTimeout(() => setShareText('🔗 Share'), 2000);
                return;
            } catch (err) {
                // User cancelled or error - fall through to clipboard
                if ((err as Error).name !== 'AbortError') {
                    console.error('Share failed:', err);
                }
            }
        }

        // Fallback: Copy to clipboard
        try {
            await navigator.clipboard.writeText(text);
            setShareText('✓ Copied!');
            setTimeout(() => setShareText('🔗 Share'), 2000);
        } catch (err) {
            console.error('Clipboard failed:', err);
            setShareText('✗ Failed');
            setTimeout(() => setShareText('🔗 Share'), 2000);
        }
    };

    return (
        <div className="container">
            <header className="header">
                <h1 className="title">Hördle #{dailyPuzzle.puzzleNumber}{genre ? ` / ${genre}` : ''}</h1>
                <div style={{ fontSize: '0.9rem', color: '#666', marginTop: '-0.5rem', marginBottom: '1rem' }}>
                    Next puzzle in: {timeUntilNext}
                </div>
            </header>

            <main className="game-board">

                <div style={{ borderBottom: '1px solid #e5e7eb', paddingBottom: '1rem' }}>
                    <div className="status-bar">
                        <span>Attempt {gameState.guesses.length + 1} / {maxAttempts}</span>
                        <span>{unlockedSeconds}s unlocked</span>
                    </div>
                    <AudioPlayer
                        src={dailyPuzzle.audioUrl}
                        unlockedSeconds={unlockedSeconds}
                        startTime={dailyPuzzle.startTime}
                        autoPlay={lastAction === 'SKIP'}
                    />
                </div>

                <div className="guess-list">
                    {gameState.guesses.map((guess, i) => {
                        const isCorrect = hasWon && i === gameState.guesses.length - 1;
                        return (
                            <div key={i} className="guess-item">
                                <span className="guess-number">#{i + 1}</span>
                                <span className={`guess-text ${guess === 'SKIPPED' ? 'skipped' : ''} ${isCorrect ? 'correct' : ''}`}>
                                    {isCorrect ? 'Correct!' : guess}
                                </span>
                            </div>
                        );
                    })}
                </div>

                {!hasWon && !hasLost && (
                    <>
                        <GuessInput onGuess={handleGuess} disabled={isProcessingGuess} />
                        {gameState.guesses.length < 6 ? (
                            <button
                                onClick={handleSkip}
                                className="skip-button"
                            >
                                Skip (+{unlockSteps[Math.min(gameState.guesses.length + 1, unlockSteps.length - 1)] - unlockedSeconds}s)
                            </button>
                        ) : (
                            <button
                                onClick={handleGiveUp}
                                className="skip-button"
                                style={{
                                    background: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
                                    boxShadow: '0 4px 15px rgba(245, 87, 108, 0.4)'
                                }}
                            >
                                Solve (Give Up)
                            </button>
                        )}
                    </>
                )}

                {hasWon && (
                    <div className="message-box success">
                        <h2 style={{ fontSize: '1.5rem', fontWeight: 'bold', marginBottom: '0.5rem' }}>You won!</h2>
                        <p>Come back tomorrow for a new song.</p>

                        {/* Song Details */}
                        <div style={{ margin: '1.5rem 0', padding: '1rem', background: 'rgba(255,255,255,0.5)', borderRadius: '0.5rem', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                            {dailyPuzzle.coverImage && (
                                <img
                                    src={dailyPuzzle.coverImage}
                                    alt="Album Cover"
                                    style={{ width: '150px', height: '150px', objectFit: 'cover', borderRadius: '0.5rem', marginBottom: '1rem', boxShadow: '0 4px 6px rgba(0,0,0,0.1)' }}
                                />
                            )}
                            <h3 style={{ fontSize: '1.125rem', fontWeight: 'bold', margin: '0 0 0.5rem 0' }}>{dailyPuzzle.title}</h3>
                            <p style={{ fontSize: '0.875rem', color: '#666', margin: '0 0 1rem 0' }}>{dailyPuzzle.artist}</p>
                            <audio controls style={{ width: '100%' }}>
                                <source src={dailyPuzzle.audioUrl} type="audio/mpeg" />
                                Your browser does not support the audio element.
                            </audio>
                        </div>

                        {statistics && <Statistics statistics={statistics} />}
                        <button onClick={handleShare} className="btn-primary" style={{ marginTop: '1rem' }}>
                            {shareText}
                        </button>
                    </div>
                )}

                {hasLost && (
                    <div className="message-box failure">
                        <h2 style={{ fontSize: '1.5rem', fontWeight: 'bold', marginBottom: '0.5rem' }}>Game Over</h2>
                        <p>The song was:</p>

                        {/* Song Details */}
                        <div style={{ margin: '1.5rem 0', padding: '1rem', background: 'rgba(255,255,255,0.5)', borderRadius: '0.5rem', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                            {dailyPuzzle.coverImage && (
                                <img
                                    src={dailyPuzzle.coverImage}
                                    alt="Album Cover"
                                    style={{ width: '150px', height: '150px', objectFit: 'cover', borderRadius: '0.5rem', marginBottom: '1rem', boxShadow: '0 4px 6px rgba(0,0,0,0.1)' }}
                                />
                            )}
                            <h3 style={{ fontSize: '1.125rem', fontWeight: 'bold', margin: '0 0 0.5rem 0' }}>{dailyPuzzle.title}</h3>
                            <p style={{ fontSize: '0.875rem', color: '#666', margin: '0 0 1rem 0' }}>{dailyPuzzle.artist}</p>
                            <audio controls style={{ width: '100%' }}>
                                <source src={dailyPuzzle.audioUrl} type="audio/mpeg" />
                                Your browser does not support the audio element.
                            </audio>
                        </div>

                        {statistics && <Statistics statistics={statistics} />}
                        <button onClick={handleShare} className="btn-primary" style={{ marginTop: '1rem' }}>
                            {shareText}
                        </button>
                    </div>
                )}

            </main>
        </div>
    );
}
