'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter, usePathname } from 'next/navigation';
import CurateSpecialEditor, { CurateSpecial } from '@/components/CurateSpecialEditor';

export default function SpecialEditorPage() {
    const params = useParams();
    const router = useRouter();
    const pathname = usePathname();
    const specialId = params.id as string;

    // Locale aus dem Pfad ableiten (/en/..., /de/...)
    const localeFromPath = pathname?.split('/')[1] as 'de' | 'en' | undefined;
    const locale: 'de' | 'en' = localeFromPath === 'de' || localeFromPath === 'en' ? localeFromPath : 'en';

    const [special, setSpecial] = useState<CurateSpecial | null>(null);
    const [loading, setLoading] = useState(true);

    const fetchSpecial = async (showLoading = true) => {
        try {
            if (showLoading) {
                setLoading(true);
            }
            const res = await fetch(`/api/specials/${specialId}`);
            if (res.ok) {
                const data = await res.json();
                setSpecial(data);
            }
        } catch (error) {
            console.error('Error fetching special:', error);
        } finally {
            if (showLoading) {
                setLoading(false);
            }
        }
    };

    useEffect(() => {
        fetchSpecial(true);
    }, [specialId]);

    const handleSaveStartTime = async (songId: number, startTime: number) => {
        const res = await fetch(`/api/specials/${specialId}/songs`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ songId, startTime }),
        });

        if (!res.ok) {
            const errorText = await res.text().catch(() => res.statusText || 'Unknown error');
            console.error('Error updating special song (admin):', res.status, errorText);
            throw new Error(`Failed to save start time: ${errorText}`);
        } else {
            // Reload special data to update the start time in the song list
            await fetchSpecial(false);
        }
    };

    if (loading) {
        return (
            <div style={{ padding: '2rem', textAlign: 'center' }}>
                <p>Loading...</p>
            </div>
        );
    }

    if (!special) {
        return (
            <div style={{ padding: '2rem', textAlign: 'center' }}>
                <p>Special not found</p>
                <button onClick={() => router.push('/admin')}>Back to Admin</button>
            </div>
        );
    }

    return (
        <CurateSpecialEditor
            special={special}
            locale={locale}
            onBack={() => router.push('/admin')}
            onSaveStartTime={handleSaveStartTime}
            backLabel="← Back to Admin"
            headerPrefix="Edit Special:"
            noSongsSubHint="Go back to the admin dashboard to add songs to this special."
        />
    );
}

