'use client';

import { useState, useRef } from 'react';
import { X, Upload, ImagePlus, Loader2, Camera } from 'lucide-react';
import { apiUrl, thumbnailUrl } from '@/lib/api';
import ArchivePhotoPicker from './ArchivePhotoPicker';

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

interface JourneyFormProps {
    journey?: {
        id: string;
        title: string;
        description: string | null;
        startDate: string | null;
        endDate: string | null;
    };
    onSave: (journey: unknown) => void;
    onCancel: () => void;
}

export default function JourneyForm({ journey, onSave, onCancel }: JourneyFormProps) {
    const isEditing = !!journey;
    const [title, setTitle] = useState(journey?.title || '');
    const [description, setDescription] = useState(journey?.description || '');
    const [startDate, setStartDate] = useState(
        journey?.startDate ? new Date(journey.startDate).toISOString().split('T')[0] : ''
    );
    const [endDate, setEndDate] = useState(
        journey?.endDate ? new Date(journey.endDate).toISOString().split('T')[0] : ''
    );
    const [saving, setSaving] = useState(false);

    // After creation: journey id + photos
    const [savedJourneyId, setSavedJourneyId] = useState<string | null>(journey?.id || null);
    const [photos, setPhotos] = useState<JourneyPhoto[]>([]);
    const [uploading, setUploading] = useState(false);
    const [showArchivePicker, setShowArchivePicker] = useState(false);
    const fileInputRef = useRef<HTMLInputElement>(null);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!title.trim()) return;

        setSaving(true);
        try {
            const url = isEditing || savedJourneyId
                ? apiUrl(`/api/journeys/${savedJourneyId || journey!.id}`)
                : apiUrl('/api/journeys');

            const res = await fetch(url, {
                method: (isEditing || savedJourneyId) ? 'PUT' : 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    title: title.trim(),
                    description: description.trim() || null,
                    startDate: startDate || null,
                    endDate: endDate || null,
                }),
            });

            if (!res.ok) {
                const err = await res.json();
                alert(err.error || 'Failed to save journey');
                return;
            }

            const result = await res.json();

            if (!savedJourneyId) {
                // Just created — stay open for photo adding
                setSavedJourneyId(result.id);
            } else {
                // Editing — close
                onSave(result);
            }
        } catch (error) {
            console.error('Failed to save journey:', error);
            alert('Failed to save journey');
        } finally {
            setSaving(false);
        }
    };

    const handleFileUpload = async (files: FileList) => {
        if (!savedJourneyId) return;
        setUploading(true);
        try {
            const formData = new FormData();
            Array.from(files).forEach(f => formData.append('files', f));

            const res = await fetch(apiUrl(`/api/journeys/${savedJourneyId}/photos`), {
                method: 'POST',
                body: formData,
            });

            if (res.ok) {
                const data = await res.json();
                setPhotos(prev => [...prev, ...data.photos]);
            }
        } catch (error) {
            console.error('Photo upload error:', error);
        } finally {
            setUploading(false);
            if (fileInputRef.current) fileInputRef.current.value = '';
        }
    };

    const handleArchiveSelect = async (photoIds: string[]) => {
        if (!savedJourneyId) return;
        setShowArchivePicker(false);
        for (const photoId of photoIds) {
            try {
                const res = await fetch(apiUrl(`/api/journeys/${savedJourneyId}/photos`), {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ photoId }),
                });
                if (res.ok) {
                    const photo = await res.json();
                    setPhotos(prev => [...prev, photo]);
                }
            } catch (error) {
                console.error('Archive photo add error:', error);
            }
        }
    };

    const handleDeletePhoto = async (photoId: string) => {
        if (!savedJourneyId) return;
        try {
            await fetch(apiUrl(`/api/journeys/${savedJourneyId}/photos/${photoId}`), {
                method: 'DELETE',
            });
            setPhotos(prev => prev.filter(p => p.id !== photoId));
        } catch (error) {
            console.error('Photo delete error:', error);
        }
    };

    const handleDone = () => {
        // Fetch the final journey and pass it back
        fetch(apiUrl(`/api/journeys/${savedJourneyId}`))
            .then(res => res.json())
            .then(data => onSave(data))
            .catch(() => onSave({ id: savedJourneyId }));
    };

    // Step 2: Photo adding (after journey created)
    const showPhotoStep = savedJourneyId && !isEditing;

    return (
        <>
            <div className="fixed inset-0 z-50 flex items-start justify-center bg-black/40 backdrop-blur-sm p-4 overflow-y-auto">
                <div className="bg-paper rounded-xl w-full max-w-md border-2 border-foreground/10 shadow-xl my-8">
                    <div className="flex items-center justify-between p-4 border-b border-foreground/10">
                        <h2 className="font-display text-lg">
                            {showPhotoStep ? 'Add Photos' : isEditing ? 'Edit Journey' : 'New Journey'}
                        </h2>
                        <button onClick={showPhotoStep ? handleDone : onCancel} className="text-foreground/40 hover:text-foreground">
                            <X className="w-5 h-5" />
                        </button>
                    </div>

                    {showPhotoStep ? (
                        /* ── Step 2: Photos ── */
                        <div className="p-4 space-y-4">
                            <p className="text-sm text-foreground/40 font-serif italic">
                                Add photos to &ldquo;{title}&rdquo;
                            </p>

                            {/* Photo grid */}
                            {photos.length > 0 && (
                                <div className="grid grid-cols-3 gap-1.5">
                                    {photos.map(photo => (
                                        <div key={photo.id} className="relative aspect-square rounded-lg overflow-hidden group/photo">
                                            <img
                                                src={thumbnailUrl(photo.url, 'sm')}
                                                alt={photo.caption || ''}
                                                className="w-full h-full object-cover"
                                            />
                                            <button
                                                type="button"
                                                onClick={() => handleDeletePhoto(photo.id)}
                                                className="absolute top-1 right-1 w-5 h-5 bg-black/60 rounded-full
                                                           flex items-center justify-center opacity-0 group-hover/photo:opacity-100 transition-opacity"
                                            >
                                                <X className="w-3 h-3 text-white" />
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            )}

                            {/* Upload buttons */}
                            <div className="flex flex-col gap-2">
                                <button
                                    type="button"
                                    onClick={() => fileInputRef.current?.click()}
                                    disabled={uploading}
                                    className="flex items-center justify-center gap-2 w-full py-3 rounded-xl
                                               border-2 border-dashed border-foreground/15
                                               text-foreground/50 hover:border-foreground/25 hover:text-foreground/70
                                               transition-colors text-sm"
                                >
                                    {uploading ? (
                                        <>
                                            <Loader2 className="w-4 h-4 animate-spin" />
                                            Uploading...
                                        </>
                                    ) : (
                                        <>
                                            <Camera className="w-4 h-4" />
                                            Upload Photos
                                        </>
                                    )}
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setShowArchivePicker(true)}
                                    className="flex items-center justify-center gap-2 w-full py-3 rounded-xl
                                               border-2 border-dashed border-foreground/15
                                               text-foreground/50 hover:border-foreground/25 hover:text-foreground/70
                                               transition-colors text-sm"
                                >
                                    <ImagePlus className="w-4 h-4" />
                                    Pick from Archive
                                </button>
                            </div>

                            <input
                                ref={fileInputRef}
                                type="file"
                                accept="image/*"
                                multiple
                                className="hidden"
                                onChange={e => e.target.files && handleFileUpload(e.target.files)}
                            />

                            {/* Done button */}
                            <button
                                type="button"
                                onClick={handleDone}
                                className="w-full px-4 py-2.5 rounded-lg text-sm font-medium
                                           bg-foreground text-paper hover:bg-foreground/90 transition-colors"
                            >
                                {photos.length > 0 ? 'Done' : 'Skip Photos'}
                            </button>
                        </div>
                    ) : (
                        /* ── Step 1: Details ── */
                        <form onSubmit={handleSubmit} className="p-4 space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-foreground/60 mb-1">Title</label>
                                <input
                                    type="text"
                                    value={title}
                                    onChange={e => setTitle(e.target.value)}
                                    placeholder="e.g. Summer in Portugal"
                                    className="w-full px-3 py-2 bg-foreground/5 rounded-lg text-sm font-serif
                                               border border-foreground/10 focus:outline-none focus:border-foreground/30"
                                    required
                                    autoFocus
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-foreground/60 mb-1">Description</label>
                                <textarea
                                    value={description}
                                    onChange={e => setDescription(e.target.value)}
                                    placeholder="A brief story about this journey..."
                                    rows={3}
                                    className="w-full px-3 py-2 bg-foreground/5 rounded-lg text-sm font-serif
                                               border border-foreground/10 focus:outline-none focus:border-foreground/30 resize-none"
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="block text-sm font-medium text-foreground/60 mb-1">Start Date</label>
                                    <input
                                        type="date"
                                        value={startDate}
                                        onChange={e => setStartDate(e.target.value)}
                                        className="w-full px-3 py-2 bg-foreground/5 rounded-lg text-sm
                                                   border border-foreground/10 focus:outline-none focus:border-foreground/30"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-foreground/60 mb-1">End Date</label>
                                    <input
                                        type="date"
                                        value={endDate}
                                        onChange={e => setEndDate(e.target.value)}
                                        className="w-full px-3 py-2 bg-foreground/5 rounded-lg text-sm
                                                   border border-foreground/10 focus:outline-none focus:border-foreground/30"
                                    />
                                </div>
                            </div>

                            <div className="flex gap-2 pt-2">
                                <button
                                    type="button"
                                    onClick={onCancel}
                                    className="flex-1 px-4 py-2 rounded-lg text-sm font-medium
                                               text-foreground/50 hover:bg-foreground/5 transition-colors"
                                >
                                    Cancel
                                </button>
                                <button
                                    type="submit"
                                    disabled={saving || !title.trim()}
                                    className="flex-1 px-4 py-2 rounded-lg text-sm font-medium
                                               bg-foreground text-paper hover:bg-foreground/90 transition-colors
                                               disabled:opacity-40 disabled:cursor-not-allowed"
                                >
                                    {saving ? 'Saving...' : isEditing ? 'Save' : 'Next: Add Photos'}
                                </button>
                            </div>
                        </form>
                    )}
                </div>
            </div>

            {showArchivePicker && (
                <ArchivePhotoPicker
                    onSelect={handleArchiveSelect}
                    onClose={() => setShowArchivePicker(false)}
                    excludeIds={photos.filter(p => p.photoId).map(p => p.photoId!)}
                />
            )}
        </>
    );
}
