import LedDisplay from '@/components/Display/LedDisplay';
import InlineForm from '@/components/Display/InlineForm';
import ProgressBar from '@/components/Display/ProgressBar';
import StatsBox from '@/components/Display/StatsBox';
import { Head } from '@inertiajs/react';
import { useEffect, useState } from 'react';

interface PurchaseSummary {
    total_shares: number;
    total_investment: number;
    average_cost_per_share: number;
}

interface CurrentPrice {
    current_price: number | null;
}

interface Milestone {
    target: number;
    description: string;
    created_at: string;
}

export default function Dashboard() {
    const [purchaseData, setPurchaseData] = useState<PurchaseSummary>({
        total_shares: 0,
        total_investment: 0,
        average_cost_per_share: 0,
    });
    
    const [priceData, setPriceData] = useState<CurrentPrice>({
        current_price: null,
    });
    
    const [milestones, setMilestones] = useState<Milestone[]>([]);
    const [showProgressBar, setShowProgressBar] = useState(false);
    const [showStatsBox, setShowStatsBox] = useState(false);
    const [activeForm, setActiveForm] = useState<'purchase' | 'milestone' | null>(null);
    const [loading, setLoading] = useState(true);

    // Fetch purchase summary, current price, and milestones
    useEffect(() => {
        const fetchData = async () => {
            try {
                const [purchaseResponse, priceResponse, milestonesResponse] = await Promise.all([
                    fetch('/purchases/summary'),
                    fetch('/pricing/current'),
                    fetch('/milestones'),
                ]);

                if (purchaseResponse.ok) {
                    const purchases = await purchaseResponse.json();
                    setPurchaseData(purchases);
                }

                if (priceResponse.ok) {
                    const price = await priceResponse.json();
                    setPriceData(price);
                }

                if (milestonesResponse.ok) {
                    const milestonesData = await milestonesResponse.json();
                    setMilestones(milestonesData);
                }
            } catch (error) {
                console.error('Failed to fetch data:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, []);

    // Refresh data after successful purchase
    const handlePurchaseSuccess = async () => {
        try {
            const purchaseResponse = await fetch('/purchases/summary');
            if (purchaseResponse.ok) {
                const purchases = await purchaseResponse.json();
                setPurchaseData(purchases);
            }
        } catch (error) {
            console.error('Failed to refresh purchase data:', error);
        }
    };

    // Refresh milestones after successful creation
    const handleMilestoneSuccess = async () => {
        try {
            const milestonesResponse = await fetch('/milestones');
            if (milestonesResponse.ok) {
                const milestonesData = await milestonesResponse.json();
                setMilestones(milestonesData);
            }
        } catch (error) {
            console.error('Failed to refresh milestone data:', error);
        }
    };


    // Calculate portfolio stats
    const currentValue = priceData.current_price 
        ? purchaseData.total_shares * priceData.current_price 
        : undefined;
    
    const profitLoss = currentValue 
        ? currentValue - purchaseData.total_investment 
        : undefined;
    
    const profitLossPercentage = profitLoss && purchaseData.total_investment > 0
        ? (profitLoss / purchaseData.total_investment) * 100
        : undefined;

    const statsData = {
        totalShares: purchaseData.total_shares,
        totalInvestment: purchaseData.total_investment,
        averageCostPerShare: purchaseData.average_cost_per_share,
        currentPrice: priceData.current_price || undefined,
        currentValue,
        profitLoss,
        profitLossPercentage,
    };

    if (loading) {
        return (
            <>
                <Head title="Dashboard" />
                <div className="min-h-screen bg-black flex items-center justify-center">
                    <div className="text-red-500 font-mono text-lg animate-pulse">
                        LOADING...
                    </div>
                </div>
            </>
        );
    }

    // Toggle handlers with cascading behavior
    const handleLedClick = () => {
        const newShowProgressBar = !showProgressBar;
        setShowProgressBar(newShowProgressBar);
        if (!newShowProgressBar) {
            // If hiding progress bar, also hide stats box
            setShowStatsBox(false);
        }
    };

    const handleProgressClick = () => {
        setShowStatsBox(!showStatsBox);
    };

    return (
        <>
            <Head title="VWCE Tracker" />
            
            {/* Stacked Layout */}
            <div className="min-h-screen bg-black">
                <div className="w-full max-w-4xl mx-auto px-4">
                    {/* Box 1: LED Number Display - Fixed position from top */}
                    <div className="pt-32">
                        <LedDisplay 
                            value={purchaseData.total_shares}
                            onClick={handleLedClick}
                        />
                    </div>
                    
                    {/* Box 2: Progress Bar (toggleable) */}
                    <div className="mt-4" style={{ display: showProgressBar ? 'block' : 'none' }}>
                        <ProgressBar 
                            onClick={handleProgressClick}
                        />
                    </div>
                    
                    {/* Box 3: Stats Box (toggleable) */}
                    <div className="mt-4" style={{ display: showStatsBox ? 'block' : 'none' }}>
                        <StatsBox 
                            stats={statsData}
                            milestones={milestones}
                            onAddPurchase={() => setActiveForm('purchase')}
                            onAddMilestone={() => setActiveForm('milestone')}
                        />
                    </div>
                    
                    {/* Box 4: Forms (only when active form is set) */}
                    <div className="mt-4" style={{ display: activeForm ? 'block' : 'none' }}>
                        <InlineForm
                            type={activeForm}
                            onClose={() => setActiveForm(null)}
                            onPurchaseSuccess={handlePurchaseSuccess}
                            onMilestoneSuccess={handleMilestoneSuccess}
                        />
                    </div>
                </div>
            </div>
        </>
    );
}
