import React, { useState, useEffect } from 'react';
import { useParams, useLocation } from 'react-router-dom';
import ProjectWorkspaceComponent from '../components/project/ProjectWorkspace';
import { getProject } from '../api/client';

const ProjectWorkspace: React.FC = () => {
    const { id } = useParams();
    const location = useLocation();
    const [project, setProject] = useState<any>(null);
    const [loading, setLoading] = useState(true);

    const fetchProject = () => {
        if (id) {
            getProject(id).then(data => {
                setProject(data);
                setLoading(false);
            }).catch(err => {
                console.error(err);
                setLoading(false);
            });
        }
    };

    useEffect(() => {
        fetchProject();
    }, [id]);

    const projectName = project?.title || location.state?.projectName || 'Nieznany Projekt';
    let projectStatus = 'Ładowanie';
    if (project) {
        if (project.status === 'completed') projectStatus = 'Gotowy';
        else if (project.status === 'in_progress') projectStatus = 'W Trakcie';
        else {
            const approvedCount = project.sections?.filter((s: any) => s.is_approved).length || 0;
            const filledCount = project.sections?.filter((s: any) => s.content && s.content.length > 50).length || 0;
            if (approvedCount > 0 || filledCount > 0) projectStatus = 'W Trakcie';
            else projectStatus = 'Szkic';
        }
    }

    if (loading) {
        return (
            <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center', color: 'var(--text-muted)' }}>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1rem' }}>
                    <div style={{ width: '40px', height: '40px', border: '3px solid rgba(16,185,129,0.2)', borderTopColor: 'var(--accent-green)', borderRadius: '50%', animation: 'spin 1s linear infinite' }} />
                    <p>Ładowanie szczegółów projektu...</p>
                </div>
                <style>{`@keyframes spin { 100% { transform: rotate(360deg); } }`}</style>
            </div>
        );
    }

    if (!project) {
        return <div style={{ color: 'red', padding: '2rem' }}>Nie udało się załadować projektu.</div>
    }

    return <ProjectWorkspaceComponent project={project} statusLabel={projectStatus} onRefresh={fetchProject} />;
};

export default ProjectWorkspace;
