import type { Component } from 'solid-js';
import { createSignal, Show, For, createEffect } from 'solid-js';
import { Portal } from 'solid-js/web';
import { X, FileBox, CheckCircle2 } from 'lucide-solid';
import { pb, COLLECTIONS } from '../../utils/db';

interface TemplateLoadModalProps {
    show: boolean;
    onClose: () => void;
    onLoad: (template: any) => void;
}

const TemplateLoadModal: Component<TemplateLoadModalProps> = (props) => {
    const [templates, setTemplates] = createSignal<any[]>([]);
    const [isLoading, setIsLoading] = createSignal(false);

    createEffect(() => {
        if (props.show) {
            loadTemplates();
        }
    });

    const loadTemplates = async () => {
        setIsLoading(true);
        try {
            const records = await pb.collection(COLLECTIONS.TEMPLATES).getFullList({
                sort: '-created'
            });
            setTemplates(records);
        } catch (err) {
            console.error(err);
            alert('Failed to load templates.');
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <Show when={props.show}>
            <Portal>
                <div class="fixed inset-0 z-[100] flex flex-col items-center justify-center bg-background/80 backdrop-blur-sm p-4 animate-in fade-in duration-200">
                    <div class="bg-card w-full max-w-2xl max-h-[85vh] flex flex-col rounded-3xl shadow-premium border border-border overflow-hidden animate-in zoom-in-95 duration-200">
                        <div class="flex items-center justify-between p-6 border-b border-border">
                            <div class="flex items-center gap-3">
                                <div class="p-2 bg-primary/10 text-primary rounded-xl">
                                    <FileBox class="w-5 h-5" />
                                </div>
                                <div>
                                    <h3 class="text-xl font-black text-foreground">Load Template</h3>
                                    <p class="text-[10px] uppercase font-bold text-muted-foreground tracking-wider mt-0.5">Select a template to edit</p>
                                </div>
                            </div>
                            <button onClick={props.onClose} class="p-2 hover:bg-muted rounded-xl transition-colors">
                                <X class="w-5 h-5 text-muted-foreground" />
                            </button>
                        </div>
                        
                        <div class="flex-1 flex flex-col p-6 gap-6 overflow-hidden">
                            {/* Templates List */}
                            <div class="flex-1 flex flex-col min-h-0 space-y-3">
                                <label class="text-xs font-black text-muted-foreground uppercase tracking-wider">Saved Templates</label>
                                <div class="flex-1 overflow-y-auto space-y-3 bg-muted/10 border border-border/50 rounded-2xl p-4">
                                    <Show
                                        when={!isLoading()}
                                        fallback={<div class="py-12 text-center text-muted-foreground text-sm font-medium">Loading templates...</div>}
                                    >
                                        <For each={templates()}>
                                            {(record) => (
                                                <div class="group flex items-center justify-between p-4 rounded-xl border border-border/60 bg-card hover:border-primary/50 hover:shadow-premium transition-all">
                                                    <div>
                                                        <h4 class="font-bold text-foreground">{record.name}</h4>
                                                        <p class="text-[10px] text-muted-foreground font-medium uppercase tracking-wider mt-1">
                                                            {record.items?.length || 0} Items • {new Date(record.created).toLocaleDateString()}
                                                        </p>
                                                    </div>
                                                    <button
                                                        onClick={() => {
                                                            props.onLoad(record);
                                                            props.onClose();
                                                        }}
                                                        class="flex items-center gap-2 px-4 py-2 bg-primary/10 text-primary border border-primary/20 rounded-lg text-xs font-bold shadow-sm hover:bg-primary hover:text-primary-foreground hover:border-primary transition-all"
                                                    >
                                                        <CheckCircle2 class="w-4 h-4" /> Load
                                                    </button>
                                                </div>
                                            )}
                                        </For>
                                        <Show when={templates().length === 0}>
                                            <div class="py-12 flex flex-col items-center justify-center text-center text-muted-foreground/60 border-2 border-dashed border-border/60 rounded-xl bg-background/50 h-full">
                                                <FileBox class="w-8 h-8 mb-3 opacity-50" />
                                                <p class="text-sm font-medium">No saved templates found.</p>
                                            </div>
                                        </Show>
                                    </Show>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </Portal>
        </Show>
    );
};

export default TemplateLoadModal;
