import React, { useState, useEffect } from 'react';
import { useGame } from '../../contexts/GameContext';
import { GameModal } from './GameModal';
import { GameButton } from '../common/GameButton';
import { useNotification } from '../../contexts/NotificationContext';
import './QuestJournal.css';
import axios from 'axios';

interface Quest {
    quest_id: string;
    title: { [key: string]: string } | string;
    description: { [key: string]: string } | string;
    status: string;
    progress: { [key: string]: number };
    objectives: any[];
    rewards: any;
    type: string;
    completion_text?: { [key: string]: string } | string;
    completed_at?: number;
    started_at?: number;
    giver_name?: { [key: string]: string } | string;
    giver_location_id?: string;
    giver_location_name?: { [key: string]: string } | string;
    giver_image?: string;
}

interface QuestJournalProps {
    onClose: () => void;
}

import { GAME_API_URL } from '../../config';
import { useTranslation } from 'react-i18next';

export const QuestJournal: React.FC<QuestJournalProps> = ({ onClose }) => {
    const { t } = useTranslation();
    const { locale, state } = useGame();
    const { addNotification } = useNotification();

    // Tabs
    const [activeTab, setActiveTab] = useState<'active' | 'completed'>('active');

    // Selection - now using a composite key
    const [selectedQuestKey, setSelectedQuestKey] = useState<string | null>(null);

    // Search
    const [searchQuery, setSearchQuery] = useState('');

    // Data
    const [activeQuests, setActiveQuests] = useState<Quest[]>([]);
    const [historyQuests, setHistoryQuests] = useState<Quest[]>([]);

    // Pagination for History
    const [historyPage, setHistoryPage] = useState(1);
    const [historyTotalPages, setHistoryTotalPages] = useState(1);
    const [loadingHistory, setLoadingHistory] = useState(false);

    // Initial Load of Active Quests from Game State
    useEffect(() => {
        if (state.quests && state.quests.active) {
            setActiveQuests(state.quests.active as Quest[]);
        }
    }, [state.quests]);

    // Fetch History when tab changes to completed or page changes
    useEffect(() => {
        if (activeTab === 'completed') {
            fetchHistory(historyPage);
        }
    }, [activeTab, historyPage]);

    const fetchHistory = async (page: number) => {
        setLoadingHistory(true);
        try {
            const token = localStorage.getItem('token');
            const response = await axios.get(`${GAME_API_URL}/quests/history`, {
                params: { page, limit: 10 }, // 10 per page for better UI fit
                headers: { Authorization: `Bearer ${token}` }
            });

            setHistoryQuests(response.data.data);
            setHistoryTotalPages(response.data.pages);
            setHistoryPage(response.data.page);
        } catch (error) {
            console.error("Failed to fetch quest history", error);
            addNotification(t('common.error'), "error");
        } finally {
            setLoadingHistory(false);
        }
    };

    const getLocalizedText = (textObj: any) => {
        if (typeof textObj === 'string') return textObj;
        if (!textObj) return '';
        return textObj[locale] || textObj['en'] || Object.values(textObj)[0] || '';
    };

    // Filter Logic
    const getFilteredQuests = () => {
        const source = activeTab === 'active' ? activeQuests : historyQuests;
        if (!searchQuery) return source;
        return source.filter(q => {
            const title = getLocalizedText(q.title).toLowerCase();
            return title.includes(searchQuery.toLowerCase());
        });
    };

    const getQuestKey = (quest: Quest) => {
        return quest.quest_id + (quest.completed_at ? `_${quest.completed_at}` : `_${quest.started_at || ''}`);
    };

    const filteredQuests = getFilteredQuests();
    const selectedQuest = filteredQuests.find(q => getQuestKey(q) === selectedQuestKey) || (filteredQuests.length > 0 ? filteredQuests[0] : null);

    // Automatically select first if selection is invalid/null or tab changes
    useEffect(() => {
        if (filteredQuests.length > 0) {
            const currentKeyValid = selectedQuestKey && filteredQuests.some(q => getQuestKey(q) === selectedQuestKey);
            if (!currentKeyValid) {
                setSelectedQuestKey(getQuestKey(filteredQuests[0]));
            }
        } else {
            setSelectedQuestKey(null);
        }
    }, [filteredQuests, activeTab]); // Re-run when list changes or tab changes


    // Renderers
    const renderObjectives = (quest: Quest) => {
        if (!quest.objectives) return null;

        // GLOBAL QUEST RENDERING
        if (quest.type === 'global') {
            return quest.objectives.map((obj, idx) => {
                const required = obj.count;
                // Personal Progress
                const personalCurrent = quest.progress?.[obj.target] || 0;

                // Global Progress
                // @ts-ignore - dynamic field
                const globalProgressMap = quest.global_progress || {};
                const globalCurrent = globalProgressMap[obj.target] || 0;
                const isGlobalComplete = (quest as any).global_is_completed || globalCurrent >= required;

                let label = obj.target;
                if (obj.target_name) {
                    const targetName = getLocalizedText(obj.target_name);
                    label = targetName; // usually simplified for global counters? e.g. "Wood"
                }

                return (
                    <li key={idx} className="objective-item global-objective">
                        <div className="objective-label">
                            <strong>{label}</strong>
                            {isGlobalComplete ? <span className="completed-badge">✅ {t('common.completed')}</span> : null}
                        </div>

                        {/* Global Progress Bar */}
                        <div className="global-progress-container">
                            <div className="progress-label">
                                <span>{t('journal.communityProgress')}</span>
                                <span>{globalCurrent} / {required}</span>
                            </div>
                            <div className="progress-bar-bg">
                                <div
                                    className="progress-bar-fill global"
                                    style={{ width: `${Math.min(100, (globalCurrent / required) * 100)}%` }}
                                ></div>
                            </div>
                        </div>

                        {/* Personal Contribution */}
                        <div className="personal-contribution">
                            <span>{t('journal.yourContribution')}: </span>
                            <span className="contribution-value">{personalCurrent}</span>
                        </div>
                    </li>
                );
            });
        }

        // STANDARD QUEST RENDERING
        return quest.objectives.map((obj, idx) => {
            const required = obj.count;
            // Force completed count for history items to avoid confusing 0/X display
            const isCompleted = quest.status === 'completed' || activeTab === 'completed';
            const current = isCompleted ? required : (quest.progress?.[obj.target] || 0);
            const met = current >= required || isCompleted;

            let label = obj.target;
            // Improved translation logic
            if (obj.target_name) {
                // If we have an enriched name, use it.
                // But we still want the prefix "Fight" or "Pick Up" if applicable
                const targetName = getLocalizedText(obj.target_name);
                if (obj.type === 'kill_count') label = `${t('game.kill')} ${targetName}`;
                else if (obj.type === 'item_delivery') label = `${t('game.pickUp')} ${targetName}`;
                else label = targetName;
            } else {
                // Fallback to basic translation if no enriched name
                if (obj.type === 'kill_count') label = `${t('game.kill')} ${obj.target}`;
                else if (obj.type === 'item_delivery') label = `${t('game.pickUp')} ${obj.target}`;
            }

            return (
                <li key={idx} className={`objective-item ${met ? 'met' : ''}`}>
                    {label}: {current}/{required}
                </li>
            );
        });
    };

    const renderDate = (timestamp?: number) => {
        if (!timestamp) return 'N/A';
        return new Date(timestamp * 1000).toLocaleString(locale === 'en' ? 'en-US' : locale);
    };

    return (
        <GameModal
            title={t('journal.title')}
            onClose={onClose}
            className="quest-journal-modal"
        >
            <div className="game-modal-content" style={{ display: 'flex', flexDirection: 'column', height: '100%', padding: 0 }}>
                {/* Header / Tabs */}
                <div style={{ padding: '10px 20px', background: 'var(--game-bg-panel)', borderBottom: '1px solid var(--game-border-color)' }}>
                    <div className="tab-container">
                        <button
                            className={`journal-tab ${activeTab === 'active' ? 'active' : ''}`}
                            onClick={() => setActiveTab('active')}
                        >
                            {t('journal.activeQuests')}
                        </button>
                        <button
                            className={`journal-tab ${activeTab === 'completed' ? 'active' : ''}`}
                            onClick={() => setActiveTab('completed')}
                        >
                            {t('journal.history')}
                        </button>
                    </div>
                </div>

                {/* Main Content Area */}
                <div className="journal-layout">
                    {/* LEFT COLUMN: LIST */}
                    <div className="quest-list-column">
                        <div className="game-search-container">
                            <span className="game-search-icon">🔍</span>
                            <input
                                type="text"
                                className="game-search-input"
                                placeholder={t('journal.searchPlaceholder')}
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                            />
                        </div>

                        <div className="quest-list-scroll">
                            {filteredQuests.length === 0 ? (
                                <div style={{ padding: '20px', color: '#777', textAlign: 'center' }}>
                                    {loadingHistory ? t('common.loading') : t('journal.noQuests')}
                                </div>
                            ) : (
                                filteredQuests.map(quest => {
                                    const key = getQuestKey(quest);
                                    return (
                                        <div
                                            key={key}
                                            className={`quest-list-item ${selectedQuestKey === key ? 'selected' : ''}`}
                                            onClick={() => setSelectedQuestKey(key)}
                                        >
                                            <h4>{getLocalizedText(quest.title)}</h4>
                                            <span className="quest-card-type">
                                                {quest.type === 'global' ? t('journal.global') : (quest.type === 'story' ? t('journal.story') : t('journal.side'))}
                                            </span>
                                            <div className={`quest-status-indicator status-${quest.status === 'active' ? 'active' : 'completed'}`}></div>
                                        </div>
                                    );
                                })
                            )}
                        </div>

                        {/* Pagination Controls for History */}
                        {activeTab === 'completed' && (
                            <div className="pagination-controls">
                                <GameButton
                                    className="pagination-btn"
                                    size="sm"
                                    disabled={historyPage <= 1 || loadingHistory}
                                    onClick={() => setHistoryPage(p => p - 1)}
                                >
                                    &laquo; {t('common.prev')}
                                </GameButton>
                                <span style={{ color: '#aaa', fontSize: '0.8rem' }}>
                                    {loadingHistory ? '...' : `${historyPage} / ${historyTotalPages}`}
                                </span>
                                <GameButton
                                    className="pagination-btn"
                                    size="sm"
                                    disabled={historyPage >= historyTotalPages || loadingHistory}
                                    onClick={() => setHistoryPage(p => p + 1)}
                                >
                                    {t('common.next')} &raquo;
                                </GameButton>
                            </div>
                        )}
                    </div>

                    {/* RIGHT COLUMN: DETAILS */}
                    <div className="quest-details-column">
                        {selectedQuest ? (
                            <>
                                <div className="quest-details-header">
                                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                                        <h2>{getLocalizedText(selectedQuest.title)}</h2>
                                        {activeTab === 'active' && selectedQuest.status === 'completed' && (
                                            <span style={{ color: '#ffd700', fontWeight: 'bold' }}>{t('journal.ready')}</span>
                                        )}
                                    </div>

                                    {/* Subtitle removed to avoid redundancy as requested */}

                                    {/* Giver Info */}
                                    {selectedQuest.giver_name && (
                                        <div className="quest-giver-info">
                                            {selectedQuest.giver_image && (
                                                <img
                                                    src={`/${selectedQuest.giver_image}`}
                                                    className="quest-giver-image"
                                                    alt="Giver"
                                                />
                                            )}
                                            <div className="quest-giver-details">
                                                <div>
                                                    <span className="label">{t('journal.giver')}:</span>
                                                    <span className="value">{getLocalizedText(selectedQuest.giver_name)}</span>
                                                </div>
                                                {(selectedQuest.giver_location_name || selectedQuest.giver_location_id) && (
                                                    <div>
                                                        <span className="label">{t('journal.location')}:</span>
                                                        <span className="value">
                                                            {selectedQuest.giver_location_name
                                                                ? getLocalizedText(selectedQuest.giver_location_name)
                                                                : selectedQuest.giver_location_id
                                                            }
                                                        </span>
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    )}
                                </div>

                                <div className="quest-description">
                                    {getLocalizedText(selectedQuest.description)}
                                </div>

                                {/* Objectives - Show for both active and completed */}
                                <div className="quest-section-title">{t('journal.objectives')}</div>
                                <ul className="objective-list">
                                    {renderObjectives(selectedQuest)}
                                </ul>

                                {selectedQuest.status === 'completed' && selectedQuest.completion_text && (
                                    <>
                                        <div className="quest-section-title">{t('journal.completionMessage')}</div>
                                        <div className="completion-text" style={{ fontStyle: 'italic', color: '#aaa', padding: '10px', background: 'rgba(0,0,0,0.2)' }}>
                                            "{getLocalizedText(selectedQuest.completion_text)}"
                                        </div>
                                    </>
                                )}

                                {selectedQuest.rewards && (
                                    <>
                                        <div className="quest-section-title">{t('journal.rewards')}</div>
                                        <ul className="rewards-list">
                                            {selectedQuest.rewards.xp && <li>{selectedQuest.rewards.xp} {t('stats.xp')}</li>}
                                            {(selectedQuest as any).reward_items_details ?
                                                Object.values((selectedQuest as any).reward_items_details).map((item: any, idx) => (
                                                    <li key={idx}>{getLocalizedText(item.name)} x{item.qty}</li>
                                                ))
                                                :
                                                selectedQuest.rewards.items && Object.entries(selectedQuest.rewards.items).map(([id, qty]) => (
                                                    <li key={id}>{id} x{qty as any}</li>
                                                ))
                                            }
                                        </ul>
                                    </>
                                )}

                                <div className="history-dates">
                                    {/* Show accepted date for both active and completed quests if available */}
                                    {selectedQuest.started_at && <div>{t('journal.accepted')}: {renderDate(selectedQuest.started_at)}</div>}
                                    {activeTab === 'completed' && selectedQuest.completed_at && <div>{t('journal.completed')}: {renderDate(selectedQuest.completed_at)}</div>}
                                </div>
                            </>
                        ) : (
                            <div className="empty-selection">{t('journal.selectQuest')}</div>
                        )}
                    </div>
                </div>
            </div>
        </GameModal >
    );
};
