'use client';

import { useState } from 'react';
import { MapPin, Calendar, Navigation } from 'lucide-react';
import { motion } from 'framer-motion';
import { thumbnailUrl } from '@/lib/api';

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

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

interface JourneyCardProps {
    journey: JourneyData;
    onClick: () => void;
    canEdit?: boolean;
    onSetCoverFocal?: (x: number, y: number) => void;
}

function formatDateRange(start: string | null, end: string | null): string {
    if (!start) return '';
    const s = new Date(start);
    const startStr = s.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
    if (!end) return startStr;
    const e = new Date(end);
    const endStr = e.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
    if (startStr === endStr) return startStr;
    return `${startStr} — ${endStr}`;
}

export default function JourneyCard({ journey, onClick, canEdit, onSetCoverFocal }: JourneyCardProps) {
    const [settingFocal, setSettingFocal] = useState(false);
    const journeyPhotos = (journey.photos || []).map(p => ({ ...p, id: p.id }));
    const stopPhotos = journey.stops.flatMap(s => s.photos);
    const allPhotos = [...journeyPhotos, ...stopPhotos];
    const previewPhotos = allPhotos.slice(0, 5);
    const locationNames = journey.stops
        .map(s => s.locationName)
        .filter(Boolean)
        .slice(0, 3);
    const dateRange = formatDateRange(journey.startDate, journey.endDate);

    // Cover: first available photo or null
    const coverUrl = journey.coverPhotoUrl || previewPhotos[0]?.url;

    return (
        <motion.div
            onClick={onClick}
            className="bg-paper rounded-xl overflow-hidden border-2 border-foreground/8 cursor-pointer
                       hover:border-foreground/15 transition-colors group"
            whileHover={{ y: -2 }}
            transition={{ duration: 0.2 }}
        >
            {/* Cover image */}
            {coverUrl && (
                <div
                    className={`relative h-48 overflow-hidden ${settingFocal ? 'cursor-crosshair' : ''}`}
                    onClick={settingFocal ? (e) => {
                        e.stopPropagation();
                        const rect = e.currentTarget.getBoundingClientRect();
                        const x = Math.round(((e.clientX - rect.left) / rect.width) * 100);
                        const y = Math.round(((e.clientY - rect.top) / rect.height) * 100);
                        onSetCoverFocal?.(x, y);
                        setSettingFocal(false);
                    } : undefined}
                >
                    <img
                        src={thumbnailUrl(coverUrl, 'lg')}
                        alt={journey.title}
                        className="w-full h-full object-cover group-hover:scale-[1.02] transition-transform duration-500"
                        style={journey.coverFocalX != null && journey.coverFocalY != null
                            ? { objectPosition: `${journey.coverFocalX}% ${journey.coverFocalY}%` }
                            : undefined
                        }
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent" />
                    {!settingFocal && (
                        <div className="absolute bottom-3 left-4 right-4">
                            <div className="flex items-center gap-1.5 text-white/80 text-xs">
                                <Navigation className="w-3.5 h-3.5" />
                                <span className="font-medium">Journey</span>
                            </div>
                        </div>
                    )}
                    {canEdit && !settingFocal && (
                        <button
                            onClick={(e) => { e.stopPropagation(); setSettingFocal(true); }}
                            className="absolute top-2 right-2 px-2 py-1 rounded-full bg-black/50 text-white/70 hover:text-white
                                       text-[10px] font-medium opacity-0 group-hover:opacity-100 transition-opacity"
                        >
                            Adjust crop
                        </button>
                    )}
                    {settingFocal && (
                        <>
                            <div className="absolute inset-0 bg-black/20 pointer-events-none" />
                            <div className="absolute bottom-3 left-1/2 -translate-x-1/2 bg-black/70 text-white text-xs px-3 py-1 rounded-full pointer-events-none">
                                Tap where the subject is
                            </div>
                            {journey.coverFocalX != null && journey.coverFocalY != null && (
                                <div className="absolute w-5 h-5 border-2 border-white rounded-full pointer-events-none shadow-lg"
                                    style={{ left: `${journey.coverFocalX}%`, top: `${journey.coverFocalY}%`, transform: 'translate(-50%, -50%)' }} />
                            )}
                        </>
                    )}
                </div>
            )}

            {/* Content */}
            <div className="p-4 space-y-3">
                {!coverUrl && (
                    <div className="flex items-center gap-1.5 text-foreground/40 text-xs mb-1">
                        <Navigation className="w-3.5 h-3.5" />
                        <span className="font-medium">Journey</span>
                    </div>
                )}

                <h3 className="font-display text-lg leading-snug text-foreground">
                    {journey.title}
                </h3>

                {dateRange && (
                    <div className="flex items-center gap-1.5 text-foreground/40 text-xs">
                        <Calendar className="w-3.5 h-3.5" />
                        <span>{dateRange}</span>
                    </div>
                )}

                {journey.description && (
                    <p className="text-sm text-foreground/50 line-clamp-2 font-serif">
                        {journey.description}
                    </p>
                )}

                {/* Location summary */}
                {locationNames.length > 0 && (
                    <div className="flex items-center gap-1.5 text-foreground/40 text-xs">
                        <MapPin className="w-3.5 h-3.5 flex-shrink-0" />
                        <span className="truncate">
                            {locationNames.join(' · ')}
                            {journey.stops.length > 3 && ` +${journey.stops.length - 3} more`}
                        </span>
                    </div>
                )}

                {/* Photo strip */}
                {previewPhotos.length > 0 && (
                    <div className="flex gap-1.5 overflow-x-auto pb-1 -mx-1 px-1">
                        {previewPhotos.map(photo => (
                            <div
                                key={photo.id}
                                className="w-16 h-16 rounded-lg overflow-hidden flex-shrink-0 border border-foreground/8"
                            >
                                <img
                                    src={thumbnailUrl(photo.url, 'sm')}
                                    alt={photo.caption || ''}
                                    className="w-full h-full object-cover grayscale group-hover:grayscale-0 transition-all duration-500"
                                />
                            </div>
                        ))}
                        {allPhotos.length > 5 && (
                            <div className="w-16 h-16 rounded-lg bg-foreground/5 flex items-center justify-center flex-shrink-0 border border-foreground/8">
                                <span className="text-xs text-foreground/30 font-medium">
                                    +{allPhotos.length - 5}
                                </span>
                            </div>
                        )}
                    </div>
                )}

                {/* Footer */}
                <div className="flex items-center justify-between text-xs text-foreground/30 pt-1">
                    <span>{journey.stops.length} stop{journey.stops.length !== 1 ? 's' : ''}</span>
                    {journey.user.name && (
                        <span className="italic font-serif">by {journey.user.name}</span>
                    )}
                </div>
            </div>
        </motion.div>
    );
}
