import LedDisplay from '@/components/Display/LedDisplay';
import SetCountForm from '@/components/Counter/SetCountForm';
import OnboardingFlow from '@/components/Onboarding/OnboardingFlow';
import TerminalSpinner from '@/components/ui/TerminalSpinner';
import { csrfToken } from '@/lib/utils';
import { Head } from '@inertiajs/react';
import { useCallback, useEffect, useState } from 'react';

export default function Dashboard() {
    const [count, setCount] = useState(0);
    const [formOpen, setFormOpen] = useState(false);
    const [loading, setLoading] = useState(true);
    const [incrementing, setIncrementing] = useState(false);
    const [needsOnboarding, setNeedsOnboarding] = useState(false);

    const loadData = useCallback(async () => {
        const response = await fetch('/tracker');

        if (!response.ok) {
            setNeedsOnboarding(true);
            return;
        }

        const { exists, tracker } = await response.json();

        setCount(tracker?.count ?? 0);
        setNeedsOnboarding(!exists);
    }, []);

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

        fetchData();
    }, [loadData]);

    const increment = async () => {
        if (incrementing) return;

        const previous = count;
        setIncrementing(true);
        setCount(previous + 1);

        try {
            const response = await fetch('/increment', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': csrfToken(),
                    Accept: 'application/json',
                },
            });

            if (!response.ok) {
                setCount(previous);
                return;
            }

            const { count: updated } = await response.json();
            setCount(updated);
        } catch {
            setCount(previous);
        } finally {
            setIncrementing(false);
        }
    };

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

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

    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={count} onClick={increment} />
                    </div>

                    <div className="text-center">
                        <button
                            type="button"
                            onClick={() => setFormOpen(true)}
                            className="text-red-400/60 hover:text-red-400 font-mono text-xs uppercase tracking-widest transition-colors"
                        >
                            [SET VALUE]
                        </button>
                    </div>

                    {formOpen && (
                        <SetCountForm
                            currentCount={count}
                            onClose={() => setFormOpen(false)}
                            onSuccess={setCount}
                        />
                    )}
                </div>
            </div>
        </>
    );
}
