import { useEffect, useState, useRef } from 'react';
import { listPipelines } from '../../../api';
import PipelineCard from './PipelineCard';
import PipelineStartModal from './PipelineStartModal';

export default function PipelineTab({ library, initialTrackId }) {
    const [pipelines, setPipelines] = useState([]);
    const [filter, setFilter] = useState('active');
    const [modalOpen, setModalOpen] = useState(false);
    const timer = useRef(null);

    const load = async () => {
        try {
            const r = await listPipelines(filter);
            setPipelines(r.pipelines || []);
        } catch { /* swallow */ }
    };

    useEffect(() => {
        load();
        timer.current = setInterval(load, 5000);
        return () => clearInterval(timer.current);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [filter]);

    useEffect(() => {
        if (initialTrackId) setModalOpen(true);
    }, [initialTrackId]);

    return (
        <div className="pipeline-container">
            <div className="pipeline-toolbar">
                <button className="button primary" onClick={() => setModalOpen(true)}>+ 새 파이프라인</button>
                <select value={filter} onChange={e => setFilter(e.target.value)}>
                    <option value="active">진행 중</option>
                    <option value="all">전체</option>
                </select>
            </div>
            <div className="pipeline-grid">
                {pipelines.map(p => (
                    <PipelineCard key={p.id} pipeline={p} onChanged={load} />
                ))}
                {pipelines.length === 0 && <p className="ms-empty">진행 중인 파이프라인이 없습니다</p>}
            </div>
            {modalOpen && (
                <PipelineStartModal
                    library={library}
                    initialTrackId={initialTrackId}
                    onClose={() => setModalOpen(false)}
                    onCreated={() => { setModalOpen(false); load(); }}
                />
            )}
        </div>
    );
}
