'use client';

import React, { useEffect, useState } from 'react';
import BottleDetails from '@/components/BottleDetails';
import { createClient } from '@/lib/supabase/client';
import { useAuth } from '@/context/AuthContext';
import { validateSession } from '@/services/validate-session';
import OfflineIndicator from '@/components/OfflineIndicator';
import { useParams, useSearchParams } from 'next/navigation';

export default function BottlePage() {
    const params = useParams();
    const searchParams = useSearchParams();
    const [sessionId, setSessionId] = useState<string | undefined>(undefined);
    const [userId, setUserId] = useState<string | undefined>(undefined);
    const { user, isLoading: isAuthLoading } = useAuth();
    const supabase = createClient();

    const bottleId = params?.id as string;
    const rawSessionId = searchParams?.get('session_id');

    useEffect(() => {
        if (isAuthLoading) return;

        const checkSession = async () => {
            if (rawSessionId) {
                const isValid = await validateSession(rawSessionId);
                if (isValid) {
                    setSessionId(rawSessionId);
                }
            }
        };

        if (user) {
            setUserId(user.id);
            checkSession();
        }
    }, [rawSessionId, user, isAuthLoading]);

    if (!bottleId) return null;

    return (
        <main className="min-h-screen bg-zinc-950 p-4 md:p-12 lg:p-24 space-y-6">
            <div className="max-w-4xl mx-auto flex justify-end">
                <OfflineIndicator />
            </div>
            <BottleDetails
                bottleId={bottleId}
                sessionId={sessionId}
                userId={userId}
            />
        </main>
    );
}
