// frontend/src/components/Sidebar.jsx
import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { useResume } from '../contexts/ResumeContext';
import api from '../services/api';
import { DocumentTextIcon, PlusIcon, ArrowRightOnRectangleIcon } from '@heroicons/react/24/outline';

const Sidebar = ({ activeStep, setActiveStep }) => {
    const { user, logout } = useAuth();
    const { loadResume, setResumeData, setTemplate, setCurrentResumeId } = useResume();
    const [resumes, setResumes] = useState([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        if (user) {
            fetchResumes();
        }
    }, [user]);

    const fetchResumes = async () => {
        setLoading(true);
        try {
            const response = await api.get('/resume/list');
            setResumes(response.data.resumes || []);
        } catch (error) {
            console.error('Failed to fetch resumes:', error);
        } finally {
            setLoading(false);
        }
    };

    const loadLastResume = async () => {
        try {
            const response = await api.get('/resume/last');
            if (response.data.resume) {
                loadResume(response.data.resume);
            }
        } catch (error) {
            console.error('Failed to load last resume:', error);
        }
    };

    const createNewResume = () => {
        setResumeData({
            fullName: '',
            email: '',
            jobTitle: '',
            yearsOfExperience: '',
            skills: '',
            summary: '',
            experience: [{ company: '', role: '', startDate: '', endDate: '', description: '' }],
            education: [{ school: '', degree: '', year: '' }],
        });
        setTemplate('modern');
        setCurrentResumeId(null);
        setActiveStep(1);
    };

    const steps = ['Upload', 'Edit', 'Preview', 'Download'];

    return (
        <div className="w-64 bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex flex-col h-full">
            <div className="p-6 border-b border-gray-200 dark:border-gray-700">
                <h1 className="text-xl font-bold bg-gradient-to-r from-primary-600 to-primary-800 bg-clip-text text-transparent">
                    AI Resume Builder
                </h1>
                <p className="text-sm text-gray-500 mt-1">Welcome, {user?.name || 'User'}</p>
            </div>
            
            <div className="flex-1 overflow-y-auto p-4">
                <button
                    onClick={createNewResume}
                    className="w-full btn-primary flex items-center justify-center gap-2 mb-6"
                >
                    <PlusIcon className="w-5 h-5" />
                    New Resume
                </button>
                
                <button
                    onClick={loadLastResume}
                    className="w-full btn-secondary mb-6"
                >
                    Continue Last Resume
                </button>
                
                <div className="mb-6">
                    <h3 className="font-semibold mb-3 text-gray-700 dark:text-gray-300">Steps</h3>
                    <div className="space-y-2">
                        {steps.map((step, index) => (
                            <button
                                key={step}
                                onClick={() => setActiveStep(index + 1)}
                                className={`w-full text-left px-3 py-2 rounded-lg transition ${
                                    activeStep === index + 1
                                        ? 'bg-primary-50 dark:bg-primary-900/30 text-primary-700 dark:text-primary-300 font-semibold'
                                        : 'hover:bg-gray-100 dark:hover:bg-gray-700'
                                }`}
                            >
                                {index + 1}. {step}
                            </button>
                        ))}
                    </div>
                </div>
                
                <div>
                    <h3 className="font-semibold mb-3 text-gray-700 dark:text-gray-300">My Resumes</h3>
                    {loading ? (
                        <div className="space-y-2">
                            {[1, 2, 3].map(i => (
                                <div key={i} className="h-12 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
                            ))}
                        </div>
                    ) : resumes.length === 0 ? (
                        <p className="text-gray-500 text-sm">No resumes saved yet</p>
                    ) : (
                        <div className="space-y-2">
                            {resumes.map(resume => (
                                <button
                                    key={resume.id}
                                    onClick={() => loadResume(resume)}
                                    className="w-full text-left p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition"
                                >
                                    <div className="flex items-center gap-2">
                                        <DocumentTextIcon className="w-4 h-4" />
                                        <span className="text-sm truncate">
                                            {resume.resume_data?.fullName || 'Untitled'}
                                        </span>
                                    </div>
                                    <p className="text-xs text-gray-500 mt-1">
                                        {new Date(resume.updated_at).toLocaleDateString()}
                                    </p>
                                </button>
                            ))}
                        </div>
                    )}
                </div>
            </div>
            
            <div className="p-4 border-t border-gray-200 dark:border-gray-700">
                <button onClick={logout} className="w-full btn-secondary flex items-center justify-center gap-2">
                    <ArrowRightOnRectangleIcon className="w-5 h-5" />
                    Logout
                </button>
            </div>
        </div>
    );
};

export default Sidebar;