import { useState, useEffect, useRef } from 'react';
import { Box, Container, CircularProgress, IconButton, Alert } from '@mui/material';
import { Brightness4, Brightness7, Refresh } from '@mui/icons-material';
import { fetchAllSources } from '../services/dataFetcher';
import { generateBriefing } from '../services/claudeService';
import { saveBriefing, getPreviousBriefing, hasTodaysBriefing, getTodaysBriefing } from '../services/storageService';
import { debugLog, debugWarn } from '../utils/constants';
import BriefingWidget from './widgets/BriefingWidget';
import WeatherWidget from './widgets/WeatherWidget';
import NewsWidget from './widgets/NewsWidget';
import ChatInterface from './ChatInterface';
import QuickLinksBar from './QuickLinksBar';

function Dashboard({ themeToggle, isDark }) {
    const [loading, setLoading] = useState(true);
    const [loadingStatus, setLoadingStatus] = useState('Initializing...');
    const [briefing, setBriefing] = useState('');
    const [sourceData, setSourceData] = useState({});
    const [error, setError] = useState(null);
    const [refreshing, setRefreshing] = useState(false);
    const [briefingTokenUsage, setBriefingTokenUsage] = useState(null);
    const [webpageTokenUsage, setWebpageTokenUsage] = useState(null);
    const [cacheInfo, setCacheInfo] = useState(null);
    const isLoadingRef = useRef(false);

    useEffect(() => {
        debugLog('=== Dashboard mounting, calling loadDashboard ===');
        loadDashboard();
    }, []);

    async function loadDashboard(forceRefresh = false) {
        // Prevent concurrent requests using ref for immediate check
        if (isLoadingRef.current) {
            debugLog('=== loadDashboard SKIPPED - already in progress ===');
            return;
        }
        
        isLoadingRef.current = true;
        
        try {
            debugLog('=== loadDashboard called ===');
            debugLog('Force refresh:', forceRefresh);
            setError(null);

            // Check if we already have today's briefing (unless forcing refresh)
            if (!forceRefresh && hasTodaysBriefing()) {
                debugLog('Using cached briefing from today');
                const todaysBriefing = getTodaysBriefing();
                setBriefing(todaysBriefing.briefing);
                setSourceData(todaysBriefing.sources || {});

                // Calculate cache age
                const cacheAge = Date.now() - todaysBriefing.timestamp;
                const cacheAgeMinutes = Math.floor(cacheAge / (1000 * 60));

                // Set cache info to display message
                setCacheInfo({
                    age: cacheAgeMinutes,
                    timestamp: todaysBriefing.timestamp
                });
                setBriefingTokenUsage(null); // Clear token usage when using cache
                setWebpageTokenUsage(null);

                setLoading(false);
                return;
            }

            debugLog('Fetching fresh data...');
            setLoadingStatus('Fetching weather and news sources...');

            // Fetch all configured sources
            const data = await fetchAllSources();
            debugLog('Fetched sources:', Object.keys(data.sources || {}));
            debugLog('Failed sources:', data.failed);
            setSourceData(data.sources || {});
            
            // Track webpage summarization token usage
            if (data.webpageTokenUsage) {
                setWebpageTokenUsage(data.webpageTokenUsage);
            }

            // If all sources failed, show error but continue
            if (data.failed > 0 && data.successful === 0) {
                setError('All data sources failed to load. Please check your internet connection and try again.');
            } else if (data.failed > 0) {
                setError(`${data.failed} data source(s) failed to load. Showing available data.`);
            }

            // Check if API key is configured
            const apiKey = import.meta.env.REACT_APP_ANTHROPIC_API_KEY;

            if (!apiKey || apiKey === 'sk-ant-your-key-here') {
                debugWarn('API key not configured properly');
                setBriefing('Please add your Anthropic API key to .env.local to generate briefings.');
                setLoading(false);
                return;
            }

            // Get yesterday's briefing for comparison
            const previousBriefing = getPreviousBriefing(1);
            debugLog('Previous briefing exists:', !!previousBriefing);

            // Only generate briefing if we have some data
            if (Object.keys(data.sources || {}).length > 0) {
                debugLog('Calling generateBriefing...');
                setLoadingStatus('Generating your personalized briefing with AI...');

                try {
                    // Generate today's briefing with Claude
                    const result = await generateBriefing(data, previousBriefing);
                    debugLog('Briefing generated');
                    debugLog('Condensed summary:', result.condensedSummary?.substring(0, 100) + '...');

                    // Handle result object with text, condensedSummary and usage
                    if (result && typeof result === 'object' && result.text) {
                        setBriefing(result.text);
                        setBriefingTokenUsage(result.usage);
                        setCacheInfo(null); // Clear cache info when generating fresh briefing
                        debugLog('Briefing token usage:', result.usage);
                    } else if (typeof result === 'string') {
                        // Fallback for string responses
                        setBriefing(result);
                        setCacheInfo(null);
                    }

                    // Save to localStorage with condensed summary
                    const today = new Date().toISOString().split('T')[0];
                    debugLog('Saving briefing for:', today);
                    const briefingText = result?.text || result;
                    const condensedSummary = result?.condensedSummary || null;
                    saveBriefing(today, briefingText, data.sources, condensedSummary);
                } catch (briefingError) {
                    console.error('Failed to generate briefing:', briefingError);
                    setBriefing(`Unable to generate AI briefing: ${briefingError.message}\n\nYou can still view the data widgets below.`);
                }
            } else {
                setBriefing('No data sources loaded successfully. Please check your configuration and try again.');
            }

        } catch (error) {
            console.error('Dashboard load error:', error);
            setError(`Failed to load dashboard: ${error.message}`);
        } finally {
            setLoading(false);
            setRefreshing(false);
            isLoadingRef.current = false;
            debugLog('=== loadDashboard completed ===');
        }
    }

    const handleRefresh = () => {
        setRefreshing(true);
        setLoading(true);
        setLoadingStatus('Refreshing your dashboard...');
        loadDashboard(true);
    };

    if (loading) {
        return (
            <Box display="flex" flexDirection="column" justifyContent="center" alignItems="center" minHeight="100vh" gap={2}>
                <CircularProgress />
                <p className="loading-status">{loadingStatus}</p>
            </Box>
        );
    }

    return (
        <Box sx={{ minHeight: '100vh', pb: 10 }}>
            {/* Top toolbar */}
            <Box sx={{
                position: 'fixed',
                top: 0,
                right: 0,
                p: 2,
                display: 'flex',
                gap: 1,
                zIndex: 100
            }}>
                <IconButton
                    onClick={() => {
                        localStorage.clear();
                        window.location.reload();
                    }}
                    title="Clear all cache and reload"
                    color="error"
                >
                    🗑️
                </IconButton>
                <IconButton
                    onClick={handleRefresh}
                    disabled={refreshing}
                    title="Refresh data"
                >
                    <Refresh />
                </IconButton>
                <IconButton
                    onClick={themeToggle}
                    title={isDark ? 'Switch to light mode' : 'Switch to dark mode'}
                >
                    {isDark ? <Brightness7 /> : <Brightness4 />}
                </IconButton>
            </Box>

            <Container maxWidth="xl" sx={{ pt: 4 }}>
                {error && (
                    <Alert severity="error" sx={{ mb: 2 }}>
                        {error}
                    </Alert>
                )}

                {(briefingTokenUsage || webpageTokenUsage) && (
                    <div className="token-usage-box">
                        <p className="token-usage-text">
                            <strong>Total API Usage This Refresh:</strong>
                        </p>
                        
                        {briefingTokenUsage && (
                            <p className="token-usage-text" style={{ marginTop: '8px', paddingLeft: '12px' }}>
                                • <strong>Briefing Generation:</strong> {briefingTokenUsage.input_tokens?.toLocaleString()} input + {briefingTokenUsage.output_tokens?.toLocaleString()} output = {(briefingTokenUsage.input_tokens + briefingTokenUsage.output_tokens).toLocaleString()} tokens
                                {' • '}
                                <strong>Cost:</strong> ${((briefingTokenUsage.input_tokens * 0.003 / 1000) + (briefingTokenUsage.output_tokens * 0.015 / 1000)).toFixed(4)}
                            </p>
                        )}
                        
                        {webpageTokenUsage && (
                            <p className="token-usage-text" style={{ marginTop: '8px', paddingLeft: '12px' }}>
                                • <strong>Webpage Summarization:</strong> {webpageTokenUsage.input_tokens?.toLocaleString()} input + {webpageTokenUsage.output_tokens?.toLocaleString()} output = {(webpageTokenUsage.input_tokens + webpageTokenUsage.output_tokens).toLocaleString()} tokens
                                {' • '}
                                <strong>Cost:</strong> ${((webpageTokenUsage.input_tokens * 0.003 / 1000) + (webpageTokenUsage.output_tokens * 0.015 / 1000)).toFixed(4)}
                            </p>
                        )}
                        
                        {briefingTokenUsage && webpageTokenUsage && (
                            <p className="token-usage-text" style={{ marginTop: '12px', paddingLeft: '12px', fontWeight: 600 }}>
                                <strong>Combined Total:</strong> {((briefingTokenUsage.input_tokens + webpageTokenUsage.input_tokens)).toLocaleString()} input + {((briefingTokenUsage.output_tokens + webpageTokenUsage.output_tokens)).toLocaleString()} output = {((briefingTokenUsage.input_tokens + briefingTokenUsage.output_tokens + webpageTokenUsage.input_tokens + webpageTokenUsage.output_tokens)).toLocaleString()} tokens
                                {' • '}
                                <strong>Total Cost:</strong> ${(((briefingTokenUsage.input_tokens + webpageTokenUsage.input_tokens) * 0.003 / 1000) + ((briefingTokenUsage.output_tokens + webpageTokenUsage.output_tokens) * 0.015 / 1000)).toFixed(4)}
                            </p>
                        )}
                        
                        <p className="token-usage-caption" style={{ marginTop: '8px' }}>
                            (Claude Sonnet 4 pricing: $0.003/1K input, $0.015/1K output)
                        </p>
                    </div>
                )}

                {cacheInfo && (
                    <div className="cache-info-box">
                        <p className="cache-info-text">
                            <strong>💾 Using cached results</strong> from {cacheInfo.age < 1 ? 'less than a minute' : cacheInfo.age === 1 ? '1 minute' : `${cacheInfo.age} minutes`} ago — no API costs incurred
                            {' '}
                            <span className="cache-info-caption">
                                (Click refresh to generate a new briefing)
                            </span>
                        </p>
                    </div>
                )}

                <Box className="widget-grid">
                    <QuickLinksBar />
                    <Box className="widget-row">
                        <BriefingWidget briefing={briefing} styles={{maxWidth:'50%'}}/>
                        <WeatherWidget
                            data={sourceData.weather}
                        />
                    </Box>
                    
                    {/* Render rows based on the data structure */}
                    {Object.entries(sourceData).map(([key, data]) => {
                        
                        // Skip non-array entries (like weather)
                        if (!Array.isArray(data) || data.length === 0) {
                            return null;
                        }
                        
                        return (
                            <Box key={key} sx={{ mb: 2 }}>
                                {/* Display row header if not using legacy row naming */}
                                {!key.startsWith('row') && (
                                    <h1 style={{ 
                                        marginBottom: '12px', 
                                        marginTop: '20px',
                                        color: 'inherit',
                                        fontWeight: 600
                                    }}>
                                        {key}
                                    </h1>
                                )}
                                <Box className="widget-row condensed">
                                    {data.map((widgetData, index) => (
                                        <NewsWidget
                                            key={`${key}-${index}`}
                                            data={widgetData}
                                        />
                                    ))}
                                </Box>
                            </Box>
                        );
                    })}
                </Box>
            </Container>

            {/* Fixed chat at bottom */}
            <ChatInterface briefing={briefing} sourceData={sourceData} />
        </Box>
    );
}

export default Dashboard;
