import { useState, useEffect } from 'react';
import { Plus, Edit2, Trash2, FileText, Clock, Package } from 'lucide-react';
import { taskTemplatesApi, TaskTemplate } from '../lib/taskTemplatesApi';
import TaskTemplateModal from '../components/TaskTemplateModal';
import { PageHeader, EmptyState, ActionButton, CardSkeleton } from '../components/ui/LinearPrimitives';

export default function TaskTemplatesPage() {
    const [templates, setTemplates] = useState<TaskTemplate[]>([]);
    const [loading, setLoading] = useState(true);
    const [selectedTemplate, setSelectedTemplate] = useState<TaskTemplate | null>(null);
    const [isModalOpen, setIsModalOpen] = useState(false);

    useEffect(() => {
        loadTemplates();
    }, []);

    const loadTemplates = async () => {
        setLoading(true);
        try {
            const data = await taskTemplatesApi.getAll();
            setTemplates(data);
        } catch (e) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    };

    const handleDelete = async (id: string) => {
        if (!confirm('Are you sure you want to delete this template?')) return;
        try {
            await taskTemplatesApi.delete(id);
            loadTemplates();
        } catch (e) {
            console.error(e);
        }
    };

    const handleEdit = (template: TaskTemplate) => {
        setSelectedTemplate(template);
        setIsModalOpen(true);
    };

    const handleCreate = () => {
        setSelectedTemplate(null);
        setIsModalOpen(true);
    };

    return (
        <div className="max-w-4xl mx-auto space-y-6 pb-20 animate-in">
            <PageHeader
                title="SOP Templates"
                subtitle="Standardized task templates"
                actions={
                    <button onClick={handleCreate} className="btn btn-primary">
                        <Plus size={16} />
                        <span className="hidden sm:inline">New Template</span>
                    </button>
                }
            />

            {loading ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                    {Array.from({ length: 4 }).map((_, i) => <CardSkeleton key={i} />)}
                </div>
            ) : templates.length === 0 ? (
                <EmptyState
                    icon={FileText}
                    title="No templates yet"
                    description="Create your first SOP template to get started."
                    action={
                        <button onClick={handleCreate} className="btn btn-primary">
                            <Plus size={16} />
                            Create Template
                        </button>
                    }
                />
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                    {templates.map(template => (
                        <div key={template.id} className="card card-interactive p-4 flex flex-col h-full group">
                            <div className="flex justify-between items-start mb-3">
                                <div className="flex-1 min-w-0">
                                    <h3 className="font-medium text-primary text-sm">{template.title}</h3>
                                    <span className="badge mt-1">{template.roomType}</span>
                                </div>
                                <div className="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity duration-fast">
                                    <ActionButton
                                        icon={Edit2}
                                        label="Edit"
                                        onClick={() => handleEdit(template)}
                                        variant="accent"
                                    />
                                    <ActionButton
                                        icon={Trash2}
                                        label="Delete"
                                        onClick={() => handleDelete(template.id)}
                                        variant="destructive"
                                    />
                                </div>
                            </div>

                            <p className="text-xs text-tertiary mb-4 line-clamp-2 flex-1">
                                {template.description || "No description provided."}
                            </p>

                            <div className="flex items-center gap-4 text-xs text-tertiary pt-3 border-t border-subtle">
                                <span className="flex items-center gap-1">
                                    <Clock size={12} />
                                    {template.estimatedMinutes} mins
                                </span>
                                {template.materials && template.materials.length > 0 && (
                                    <span className="flex items-center gap-1">
                                        <Package size={12} />
                                        {template.materials.length} Items
                                    </span>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {isModalOpen && (
                <TaskTemplateModal
                    template={selectedTemplate}
                    onClose={() => setIsModalOpen(false)}
                    onSuccess={loadTemplates}
                />
            )}
        </div>
    );
}
