import LedDisplay from '@/components/Display/LedDisplay';
import InlineForm from '@/components/Display/InlineForm';
import OnboardingFlow from '@/components/Onboarding/OnboardingFlow';
import TerminalSpinner from '@/components/ui/TerminalSpinner';
import { Head } from '@inertiajs/react';
import { useCallback, useEffect, useState } from 'react';
import type { Tracker } from '@/types/domain';

export default function Dashboard() {
    const [totalShares, setTotalShares] = useState(0);
    const [formOpen, setFormOpen] = useState(false);
    const [loading, setLoading] = useState(true);
    const [needsOnboarding, setNeedsOnboarding] = useState(false);
    const [tracker, setTracker] = useState<Tracker | null>(null);

    const loadData = useCallback(async () => {
        const [entriesResponse, trackerResponse] = await Promise.all([
            fetch('/entries/summary'),
            fetch('/tracker'),
        ]);

        if (entriesResponse.ok) {
            const entries = await entriesResponse.json();
            setTotalShares(entries.total_quantity);
        }

        let trackerExists = false;

        if (trackerResponse.ok) {
            const { exists, tracker: trackerData } = await trackerResponse.json();
            setTracker(trackerData ?? null);
            trackerExists = Boolean(exists);
        }

        setNeedsOnboarding(!trackerExists);
    }, []);

    useEffect(() => {
        const fetchData = async () => {
            try {
                await loadData();
            } catch (error) {
                console.error('Failed to fetch data:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [loadData]);

    const handleEntrySuccess = async () => {
        try {
            const entriesResponse = await fetch('/entries/summary');
            if (entriesResponse.ok) {
                const entries = await entriesResponse.json();
                setTotalShares(entries.total_quantity);
            }
        } catch (error) {
            console.error('Failed to refresh entry data:', error);
        }
    };

    const handleOnboardingComplete = loadData;

    if (loading) {
        return (
            <>
                <Head title="Dashboard" />
                <TerminalSpinner fullScreen />
            </>
        );
    }

    if (needsOnboarding) {
        return (
            <>
                <Head title="incr - Setup" />
                <OnboardingFlow onComplete={handleOnboardingComplete} />
            </>
        );
    }

    return (
        <>
            <Head title="incr" />

            <div className="min-h-screen bg-black">
                <div className="w-full max-w-4xl mx-auto px-4">
                    <div className="pt-32">
                        <LedDisplay
                            value={totalShares}
                            onClick={() => setFormOpen((open) => !open)}
                        />
                    </div>

                    <InlineForm
                        open={formOpen}
                        unit={tracker?.unit}
                        onClose={() => setFormOpen(false)}
                        onSuccess={handleEntrySuccess}
                    />
                </div>
            </div>
        </>
    );
}
