import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import api from '../api';
import { ArrowLeft, ArrowRight, Play } from 'lucide-react';

const NewJob: React.FC = () => {
    const navigate = useNavigate();
    const [step, setStep] = useState(1);
    const [branch, setBranch] = useState('');
    const [scenarios, setScenarios] = useState<string[]>([]);
    const [selectedScenarios, setSelectedScenarios] = useState<string[]>([]);
    const [environment, setEnvironment] = useState('Sensor hub');
    const [testMode, setTestMode] = useState('devbench-simulator');
    const [loading, setLoading] = useState(false);

    const handleBranchSubmit = async () => {
        setLoading(true);
        try {
            const response = await api.post('/jobs/scenarios', null, { params: { branch_name: branch } });
            setScenarios(response.data);
            setStep(2);
        } catch (error) {
            alert('Failed to get scenarios');
        } finally {
            setLoading(false);
        }
    };

    const handleStartJob = async () => {
        try {
            await api.post('/jobs/submit', {
                branch_name: branch,
                scenarios: selectedScenarios,
                environment,
                test_mode: testMode
            });
            navigate('/dashboard');
        } catch (error) {
            alert('Failed to submit job');
        }
    };

    return (
        <div className="min-h-screen bg-gray-100 p-8">
            <div className="max-w-2xl mx-auto bg-white rounded-lg shadow-md p-8">
                <div className="mb-8 flex items-center justify-between">
                    <h1 className="text-2xl font-bold">New Job Submission</h1>
                    <button onClick={() => navigate('/dashboard')} className="text-gray-500 hover:text-gray-700">Cancel</button>
                </div>

                {/* Progress Bar */}
                <div className="flex mb-8">
                    {[1, 2, 3, 4].map(i => (
                        <div key={i} className={`flex-1 h-2 rounded-full mx-1 ${step >= i ? 'bg-accent' : 'bg-gray-200'}`} />
                    ))}
                </div>

                {step === 1 && (
                    <div>
                        <h2 className="text-xl font-semibold mb-4">Step 1: Enter Branch Name</h2>
                        <input
                            type="text"
                            className="w-full border border-gray-300 rounded p-2 mb-4"
                            placeholder="e.g. feature/login-fix"
                            value={branch}
                            onChange={(e) => setBranch(e.target.value)}
                        />
                        <div className="flex justify-end">
                            <button
                                onClick={handleBranchSubmit}
                                disabled={!branch || loading}
                                className="bg-primary text-white px-4 py-2 rounded flex items-center gap-2 disabled:opacity-50"
                            >
                                {loading ? 'Loading...' : 'Next'} <ArrowRight size={16} />
                            </button>
                        </div>
                    </div>
                )}

                {step === 2 && (
                    <div>
                        <h2 className="text-xl font-semibold mb-4">Step 2: Select Scenarios</h2>
                        <div className="mb-4 max-h-60 overflow-y-auto border border-gray-200 rounded p-2">
                            {scenarios.map(s => (
                                <label key={s} className="flex items-center p-2 hover:bg-gray-50 cursor-pointer">
                                    <input
                                        type="checkbox"
                                        checked={selectedScenarios.includes(s)}
                                        onChange={(e) => {
                                            if (e.target.checked) setSelectedScenarios([...selectedScenarios, s]);
                                            else setSelectedScenarios(selectedScenarios.filter(x => x !== s));
                                        }}
                                        className="mr-2"
                                    />
                                    {s}
                                </label>
                            ))}
                        </div>
                        <div className="flex justify-between">
                            <button onClick={() => setStep(1)} className="text-gray-600 flex items-center gap-2"><ArrowLeft size={16} /> Back</button>
                            <button
                                onClick={() => setStep(3)}
                                disabled={selectedScenarios.length === 0}
                                className="bg-primary text-white px-4 py-2 rounded flex items-center gap-2 disabled:opacity-50"
                            >
                                Next <ArrowRight size={16} />
                            </button>
                        </div>
                    </div>
                )}

                {step === 3 && (
                    <div>
                        <h2 className="text-xl font-semibold mb-4">Step 3: Select Environment</h2>
                        <div className="space-y-2 mb-4">
                            {['Sensor hub', 'Main board'].map(opt => (
                                <label key={opt} className="flex items-center p-3 border rounded cursor-pointer hover:bg-gray-50">
                                    <input
                                        type="radio"
                                        name="env"
                                        checked={environment === opt}
                                        onChange={() => setEnvironment(opt)}
                                        className="mr-2"
                                    />
                                    {opt}
                                </label>
                            ))}
                        </div>
                        <div className="flex justify-between">
                            <button onClick={() => setStep(2)} className="text-gray-600 flex items-center gap-2"><ArrowLeft size={16} /> Back</button>
                            <button onClick={() => setStep(4)} className="bg-primary text-white px-4 py-2 rounded flex items-center gap-2">
                                Next <ArrowRight size={16} />
                            </button>
                        </div>
                    </div>
                )}

                {step === 4 && (
                    <div>
                        <h2 className="text-xl font-semibold mb-4">Step 4: Select Test Mode</h2>
                        <div className="space-y-2 mb-4">
                            {['devbench-simulator', 'testbench-HIL'].map(opt => (
                                <label key={opt} className="flex items-center p-3 border rounded cursor-pointer hover:bg-gray-50">
                                    <input
                                        type="radio"
                                        name="mode"
                                        checked={testMode === opt}
                                        onChange={() => setTestMode(opt)}
                                        className="mr-2"
                                    />
                                    {opt}
                                </label>
                            ))}
                        </div>
                        <div className="flex justify-between">
                            <button onClick={() => setStep(3)} className="text-gray-600 flex items-center gap-2"><ArrowLeft size={16} /> Back</button>
                            <button onClick={handleStartJob} className="bg-green-600 text-white px-6 py-2 rounded flex items-center gap-2 hover:bg-green-700">
                                <Play size={16} /> Start Job
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default NewJob;
