import React, { useEffect, useState } from 'react';
import { Box, Typography, FormControl, InputLabel, Select, MenuItem, Button, CircularProgress, Alert } from '@mui/material';
import { fetchJobs } from '../api';
import { useNavigate } from 'react-router-dom';

const JobSelectionPage = () => {
  const [jobs, setJobs] = useState([]);
  const [selectedJobNo, setSelectedJobNo] = useState('');
  const [selectedJobName, setSelectedJobName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const navigate = useNavigate();

  useEffect(() => {
    async function loadJobs() {
      setLoading(true);
      setError('');
      try {
        const res = await fetchJobs({});
        if (res.data && Array.isArray(res.data.jobs)) {
          setJobs(res.data.jobs);
        } else {
          setJobs([]);
        }
      } catch (e) {
        setError('프로젝트 목록을 불러오지 못했습니다.');
      } finally {
        setLoading(false);
      }
    }
    loadJobs();
  }, []);

  const handleSelect = (e) => {
    const jobNo = e.target.value;
    setSelectedJobNo(jobNo);
    const job = jobs.find(j => j.job_no === jobNo);
    setSelectedJobName(job ? job.job_name : '');
  };

  const handleConfirm = () => {
    if (selectedJobNo && selectedJobName) {
      navigate(`/bom-status?job_no=${selectedJobNo}&job_name=${encodeURIComponent(selectedJobName)}`);
    }
  };

  return (
    <Box sx={{ maxWidth: 500, mx: 'auto', mt: 8 }}>
      <Typography variant="h4" gutterBottom>프로젝트 선택</Typography>
      {loading && <CircularProgress sx={{ mt: 4 }} />}
      {error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}
      <FormControl size="small" fullWidth sx={{ mt: 3 }}>
        <InputLabel>프로젝트</InputLabel>
        <Select
          value={selectedJobNo}
          label="프로젝트"
          onChange={handleSelect}
          displayEmpty
        >
          <MenuItem value="">선택</MenuItem>
          {jobs.map(job => (
            <MenuItem key={job.job_no} value={job.job_no}>
              {job.job_no} ({job.job_name})
            </MenuItem>
          ))}
        </Select>
      </FormControl>
      {selectedJobNo && (
        <Alert severity="info" sx={{ mt: 3 }}>
          선택된 프로젝트: <b>{selectedJobNo} ({selectedJobName})</b>
        </Alert>
      )}
      <Button
        variant="contained"
        sx={{ mt: 4, minWidth: 120 }}
        disabled={!selectedJobNo}
        onClick={handleConfirm}
      >
        확인
      </Button>
    </Box>
  );
};

export default JobSelectionPage; 