import { useForm, router } from '@inertiajs/react';
import AppLayout from '@/layouts/AppLayout';
import { useState } from 'react';
import { useTranslator } from '@/lib/i18n';
import { ExportMenu } from '@/components/export-menu';

interface TimelineEvent {
    id: string;
    title: string;
    start_time: string;
    duration_minutes: number;
    location?: string;
    notes?: string;
}

interface Props {
    wedding: any;
    events: TimelineEvent[];
}

export default function Timeline({ wedding, events }: Props) {
    const t = useTranslator();
    const [showAdd, setShowAdd] = useState(false);
    const form = useForm({
        title: '', start_time: '09:00', duration_minutes: 30,
        location: '', notes: '',
    });

    function handleAdd(e: React.FormEvent) {
        e.preventDefault();
        form.post(`/weddings/${wedding.id}/timeline`, {
            onSuccess: () => { form.reset(); setShowAdd(false); },
            preserveScroll: true,
        });
    }

    const totalMinutes = events.reduce((s, e) => s + e.duration_minutes, 0);
    const hours = Math.floor(totalMinutes / 60);
    const mins = totalMinutes % 60;

    return (
        <AppLayout wedding={wedding}>
            <div className="max-w-3xl mx-auto px-6 py-8">
                <div className="flex items-center justify-between mb-8">
                    <div>
                        <h1 className="font-serif text-3xl">{t('timeline.title')}</h1>
                        <p className="text-sm text-muted-foreground mt-1 max-w-xl">
                            {t('timeline.intro')}
                        </p>
                        {events.length > 0 && (
                            <p className="text-xs text-muted-foreground/80 mt-1">
                                {t('timeline.total', { hours, mins })}
                            </p>
                        )}
                    </div>
                    <div className="flex items-center gap-2">
                        <ExportMenu
                            filename="timeline"
                            title={t('timeline.title')}
                            rows={events}
                            columns={[
                                { header: t('timeline.start_time'), value: (e: TimelineEvent) => e.start_time },
                                { header: t('timeline.event_title'), value: (e: TimelineEvent) => e.title },
                                { header: t('timeline.duration'), value: (e: TimelineEvent) => e.duration_minutes },
                                { header: t('timeline.location'), value: (e: TimelineEvent) => e.location },
                                { header: t('timeline.notes'), value: (e: TimelineEvent) => e.notes },
                            ]}
                        />
                        <button onClick={() => setShowAdd(true)} className="bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm">
                            + {t('timeline.add_event')}
                        </button>
                    </div>
                </div>

                {events.length === 0 ? (
                    <div className="text-center py-20 text-muted-foreground">
                        <p className="text-4xl mb-2">⏰</p>
                        <p>{t('timeline.empty')}</p>
                    </div>
                ) : (
                    <div className="relative">
                        <div className="absolute left-16 top-0 bottom-0 w-px bg-border" />
                        <div className="space-y-4">
                            {events.map(event => (
                                <div key={event.id} className="flex gap-4">
                                    <div className="w-14 text-right text-sm font-mono text-muted-foreground pt-1">{event.start_time}</div>
                                    <div className="flex-1 rounded-xl p-4 border border-border bg-card">
                                        <div className="flex items-start justify-between">
                                            <div>
                                                <p className="font-semibold text-foreground">{event.title}</p>
                                                <p className="text-xs mt-0.5 text-muted-foreground">{event.duration_minutes} min</p>
                                                {event.location && <p className="text-xs mt-0.5 text-muted-foreground">📍 {event.location}</p>}
                                                {event.notes && <p className="text-xs mt-0.5 text-muted-foreground/80">{event.notes}</p>}
                                            </div>
                                            <button onClick={() => router.delete(`/weddings/${wedding.id}/timeline/${event.id}`, { preserveScroll: true })} className="text-xs opacity-60 hover:opacity-100 ml-2">✕</button>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </div>

            {showAdd && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
                    <div className="bg-card rounded-2xl p-6 w-full max-w-md shadow-xl">
                        <div className="flex items-center justify-between mb-4">
                            <h2 className="font-serif text-xl">{t('timeline.add_event')}</h2>
                            <button onClick={() => { setShowAdd(false); form.reset(); }} className="text-muted-foreground">✕</button>
                        </div>
                        <form onSubmit={handleAdd} className="space-y-3">
                            <div>
                                <label className="block text-sm font-medium mb-1">{t('timeline.event_title')} *</label>
                                <input type="text" value={form.data.title} onChange={e => form.setData('title', e.target.value)} className="w-full border border-border rounded-lg px-3 py-2 text-sm" required />
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="block text-sm font-medium mb-1">{t('timeline.start_time')} *</label>
                                    <input type="time" value={form.data.start_time} onChange={e => form.setData('start_time', e.target.value)} className="w-full border border-border rounded-lg px-3 py-2 text-sm" required />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium mb-1">{t('timeline.duration')}</label>
                                    <input type="number" min={1} value={form.data.duration_minutes} onChange={e => form.setData('duration_minutes', Number(e.target.value))} className="w-full border border-border rounded-lg px-3 py-2 text-sm" />
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-medium mb-1">{t('timeline.location')}</label>
                                <input type="text" value={form.data.location} onChange={e => form.setData('location', e.target.value)} className="w-full border border-border rounded-lg px-3 py-2 text-sm" />
                            </div>
                            <div>
                                <label className="block text-sm font-medium mb-1">{t('timeline.notes')}</label>
                                <textarea value={form.data.notes} onChange={e => form.setData('notes', e.target.value)} className="w-full border border-border rounded-lg px-3 py-2 text-sm" rows={2} />
                            </div>
                            <div className="flex gap-3">
                                <button type="button" onClick={() => { setShowAdd(false); form.reset(); }} className="flex-1 border border-border rounded-lg py-2 text-sm">{t('common.cancel')}</button>
                                <button type="submit" disabled={form.processing} className="flex-1 bg-primary text-primary-foreground rounded-lg py-2 text-sm">{t('timeline.add_event')}</button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </AppLayout>
    );
}
