'use client';

import React, { useEffect, useState } from 'react';
import BottleDetails from '@/components/BottleDetails';
import { createClient } from '@/lib/supabase/client';
import { validateSession } from '@/services/validate-session';
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 supabase = createClient();

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

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

        const getAuth = async () => {
            const { data: { user } } = await supabase.auth.getUser();
            if (user) {
                setUserId(user.id);
            }
        };

        checkSession();
        getAuth();
    }, [rawSessionId, supabase]);

    if (!bottleId) return null;

    return (
        <main className="min-h-screen bg-zinc-50 dark:bg-black p-4 md:p-12 lg:p-24">
            <BottleDetails
                bottleId={bottleId}
                sessionId={sessionId}
                userId={userId}
            />
        </main>
    );
}
