'use client';

import { useState, useEffect } from 'react';
import { Plus, Navigation, Trash2 } from 'lucide-react';
import { useSession } from 'next-auth/react';
import { motion } from 'framer-motion';
import { apiUrl } from '@/lib/api';
import JourneyCard from './JourneyCard';
import JourneyWizard from './JourneyWizard';
import JourneyDetail from './JourneyDetail';

interface JourneyPhoto {
    id: string;
    url: string;
    caption: string | null;
}

interface JourneyStop {
    id: string;
    title: string;
    locationName: string | null;
    latitude: number | null;
    longitude: number | null;
    order: number;
    photos: JourneyPhoto[];
}

interface JourneySummary {
    id: string;
    title: string;
    description: string | null;
    coverPhotoUrl: string | null;
    coverFocalX?: number | null;
    coverFocalY?: number | null;
    startDate: string | null;
    endDate: string | null;
    createdAt: string;
    userId: string;
    user: { id: string; name: string | null };
    stops: JourneyStop[];
}

export default function JourneysView() {
    const { data: session } = useSession();
    const [journeys, setJourneys] = useState<JourneySummary[]>([]);
    const [loading, setLoading] = useState(true);
    const [showCreateForm, setShowCreateForm] = useState(false);
    const [selectedJourneyId, setSelectedJourneyId] = useState<string | null>(null);

    const canCreate = !!session?.user;

    useEffect(() => {
        fetch(apiUrl('/api/journeys'))
            .then(res => res.json())
            .then(data => {
                setJourneys(data.journeys || []);
                setLoading(false);
            })
            .catch(() => setLoading(false));
    }, []);

    const handleDelete = async (journeyId: string) => {
        if (!confirm('Delete this journey? This cannot be undone.')) return;
        try {
            const res = await fetch(apiUrl(`/api/journeys/${journeyId}`), { method: 'DELETE' });
            if (res.ok) {
                setJourneys(prev => prev.filter(j => j.id !== journeyId));
            }
        } catch (error) {
            console.error('Failed to delete journey:', error);
        }
    };

    const handleWizardComplete = (result: { id: string }) => {
        setShowCreateForm(false);
        // Refresh the list and navigate to the new journey
        fetch(apiUrl('/api/journeys'))
            .then(res => res.json())
            .then(data => {
                setJourneys(data.journeys || []);
                setSelectedJourneyId(result.id);
            })
            .catch(console.error);
    };

    // Show detail view
    if (selectedJourneyId) {
        const journey = journeys.find(j => j.id === selectedJourneyId);
        const canEdit = journey
            ? session?.user?.role === 'admin' || session?.user?.id === journey.userId
            : false;

        return (
            <JourneyDetail
                journeyId={selectedJourneyId}
                onBack={() => {
                    setSelectedJourneyId(null);
                    fetch(apiUrl('/api/journeys'))
                        .then(res => res.json())
                        .then(data => setJourneys(data.journeys || []))
                        .catch(console.error);
                }}
                canEdit={canEdit}
            />
        );
    }

    if (loading) {
        return (
            <div className="flex flex-col items-center justify-center py-20 gap-6">
                <div className="flex gap-3">
                    {[0, 1, 2].map(i => (
                        <motion.div
                            key={i}
                            className="w-14 h-10 rounded border-2 border-foreground/15 bg-foreground/5"
                            animate={{ opacity: [0.3, 0.7, 0.3] }}
                            transition={{ duration: 1.5, repeat: Infinity, delay: i * 0.2, ease: 'easeInOut' }}
                        />
                    ))}
                </div>
                <p className="text-sm text-foreground/30 italic font-serif">Loading journeys...</p>
            </div>
        );
    }

    return (
        <>
            <div className="space-y-4">
                {/* Header */}
                {canCreate && (
                    <div className="flex justify-end">
                        <button
                            onClick={() => setShowCreateForm(true)}
                            className="flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium
                                       bg-foreground text-paper hover:bg-foreground/90 transition-colors"
                        >
                            <Plus className="w-4 h-4" />
                            New Journey
                        </button>
                    </div>
                )}

                {/* Journeys */}
                <div className="space-y-4">
                    {journeys.map((journey, index) => {
                        const canDelete = session?.user?.role === 'admin' || session?.user?.id === journey.userId;
                        return (
                            <motion.div
                                key={journey.id}
                                initial={{ opacity: 0, y: 24 }}
                                whileInView={{ opacity: 1, y: 0 }}
                                viewport={{ once: true, margin: '-40px' }}
                                transition={{
                                    duration: 0.5,
                                    ease: [0.25, 1, 0.5, 1],
                                    delay: index < 3 ? index * 0.1 : 0,
                                }}
                                className="relative group"
                            >
                                <JourneyCard
                                    journey={journey}
                                    onClick={() => setSelectedJourneyId(journey.id)}
                                    canEdit={canDelete}
                                    onSetCoverFocal={async (x, y) => {
                                        try {
                                            await fetch(apiUrl(`/api/journeys/${journey.id}`), {
                                                method: 'PUT',
                                                headers: { 'Content-Type': 'application/json' },
                                                body: JSON.stringify({ coverFocalX: x, coverFocalY: y }),
                                            });
                                            setJourneys(prev => prev.map(j =>
                                                j.id === journey.id ? { ...j, coverFocalX: x, coverFocalY: y } : j
                                            ));
                                        } catch (e) {
                                            console.error('Set cover focal error:', e);
                                        }
                                    }}
                                />
                                {canDelete && (
                                    <button
                                        onClick={() => handleDelete(journey.id)}
                                        className="absolute top-3 right-3 p-1.5 rounded-full bg-paper/90 border border-foreground/10
                                                   text-foreground/25 hover:text-red-500 hover:border-red-200
                                                   opacity-0 group-hover:opacity-100 transition-all shadow-sm"
                                        title="Delete journey"
                                    >
                                        <Trash2 className="w-3.5 h-3.5" />
                                    </button>
                                )}
                            </motion.div>
                        );
                    })}
                </div>
            </div>

            {showCreateForm && (
                <JourneyWizard
                    onComplete={handleWizardComplete}
                    onCancel={() => setShowCreateForm(false)}
                />
            )}
        </>
    );
}
