'use client';

import { useState, useEffect } from 'react';
import { X, Search, Check } from 'lucide-react';
import { apiUrl, thumbnailUrl } from '@/lib/api';

interface ArchivePhoto {
    id: string;
    url: string;
    filename: string;
    caption: string | null;
}

interface ArchiveRoll {
    id: string;
    title: string;
    photos: ArchivePhoto[];
}

interface ArchivePhotoPickerProps {
    onSelect: (photoIds: string[]) => void;
    onClose: () => void;
    excludeIds?: string[];
}

export default function ArchivePhotoPicker({ onSelect, onClose, excludeIds = [] }: ArchivePhotoPickerProps) {
    const [rolls, setRolls] = useState<ArchiveRoll[]>([]);
    const [selected, setSelected] = useState<Set<string>>(new Set());
    const [search, setSearch] = useState('');
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const params = new URLSearchParams({ limit: '50' });
        if (search) params.set('search', search);

        fetch(apiUrl(`/api/feed?${params}`))
            .then(res => res.json())
            .then(data => {
                setRolls(data.rolls || []);
                setLoading(false);
            })
            .catch(() => setLoading(false));
    }, [search]);

    const togglePhoto = (photoId: string) => {
        setSelected(prev => {
            const next = new Set(prev);
            if (next.has(photoId)) {
                next.delete(photoId);
            } else {
                next.add(photoId);
            }
            return next;
        });
    };

    const handleConfirm = () => {
        onSelect(Array.from(selected));
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
            <div className="flex flex-col max-w-2xl w-full max-h-[70vh] bg-paper rounded-xl border-2 border-foreground/10 shadow-xl overflow-hidden">
                {/* Header */}
                <div className="flex items-center justify-between p-4 border-b border-foreground/10">
                    <h2 className="font-display text-lg">Pick from Archive</h2>
                    <button onClick={onClose} className="text-foreground/40 hover:text-foreground">
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {/* Search */}
                <div className="p-3 border-b border-foreground/5">
                    <div className="relative">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-foreground/30" />
                        <input
                            type="text"
                            value={search}
                            onChange={e => setSearch(e.target.value)}
                            placeholder="Search rolls..."
                            className="w-full pl-9 pr-4 py-2 bg-foreground/5 rounded-lg text-sm
                                       border border-foreground/10 focus:outline-none focus:border-foreground/30"
                        />
                    </div>
                </div>

                {/* Photos grid */}
                <div className="flex-1 overflow-y-auto p-3 space-y-4">
                    {loading ? (
                        <div className="flex justify-center py-8">
                            <div className="w-6 h-6 border-2 border-foreground/20 border-t-foreground/60 rounded-full animate-spin" />
                        </div>
                    ) : rolls.length === 0 ? (
                        <p className="text-center text-foreground/30 py-8 text-sm font-serif italic">No photos found</p>
                    ) : (
                        rolls.map(roll => (
                            <div key={roll.id}>
                                <h3 className="text-sm font-medium text-foreground/50 mb-2">{roll.title}</h3>
                                <div className="grid grid-cols-4 gap-1.5">
                                    {roll.photos
                                        .filter(p => !excludeIds.includes(p.id))
                                        .map(photo => (
                                            <button
                                                key={photo.id}
                                                type="button"
                                                onClick={() => togglePhoto(photo.id)}
                                                className={`relative aspect-square rounded-lg overflow-hidden border-2 transition-all ${
                                                    selected.has(photo.id)
                                                        ? 'border-foreground ring-1 ring-foreground/20'
                                                        : 'border-transparent hover:border-foreground/20'
                                                }`}
                                            >
                                                <img
                                                    src={thumbnailUrl(photo.url, 'sm')}
                                                    alt={photo.caption || photo.filename}
                                                    className="w-full h-full object-cover"
                                                />
                                                {selected.has(photo.id) && (
                                                    <div className="absolute inset-0 bg-foreground/30 flex items-center justify-center">
                                                        <Check className="w-5 h-5 text-paper" />
                                                    </div>
                                                )}
                                            </button>
                                        ))}
                                </div>
                            </div>
                        ))
                    )}
                </div>

                {/* Footer */}
                <div className="p-4 border-t border-foreground/10 flex items-center justify-between">
                    <span className="text-sm text-foreground/40">
                        {selected.size} selected
                    </span>
                    <button
                        onClick={handleConfirm}
                        disabled={selected.size === 0}
                        className="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"
                    >
                        Add Selected
                    </button>
                </div>
            </div>
        </div>
    );
}
