import React, { useEffect, useState } from 'react';
import { fetchJobs } from '../api';
import api from '../api';

const JobSelectionPage = ({ onJobSelect }) => {
  const [jobs, setJobs] = useState([]);
  const [selectedJobNo, setSelectedJobNo] = useState('');
  const [selectedJobName, setSelectedJobName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [editingJobNo, setEditingJobNo] = useState(null);
  const [editedName, setEditedName] = useState('');

  // 프로젝트 이름 수정
  const updateJobName = async (jobNo) => {
    try {
      const project = jobs.find(j => j.job_no === jobNo);
      if (!project) return;
      
      const response = await api.patch(`/dashboard/projects/${project.id}?job_name=${encodeURIComponent(editedName)}`);
      
      if (response.data.success) {
        // 로컬 상태 업데이트
        setJobs(jobs.map(j => 
          j.job_no === jobNo ? { ...j, job_name: editedName } : j
        ));
        
        // 선택된 프로젝트 이름도 업데이트
        if (selectedJobNo === jobNo) {
          setSelectedJobName(editedName);
        }
        
        setEditingJobNo(null);
        setEditedName('');
      }
    } catch (error) {
      console.error('프로젝트 이름 수정 실패:', error);
      alert('프로젝트 이름 수정에 실패했습니다.');
    }
  };

  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 && onJobSelect) {
      onJobSelect(selectedJobNo, selectedJobName);
    }
  };

  return (
    <div style={{ 
      padding: '32px',
      background: '#f7fafc',
      minHeight: '100vh'
    }}>
      <div style={{ maxWidth: '600px', margin: '0 auto' }}>
        <h1 style={{ 
          fontSize: '28px', 
          fontWeight: '700', 
          color: '#2d3748',
          margin: '0 0 8px 0'
        }}>
          📋 프로젝트 선택
        </h1>
        <p style={{ 
          color: '#718096', 
          fontSize: '16px',
          margin: '0 0 32px 0'
        }}>
          BOM 관리할 프로젝트를 선택하세요.
        </p>

        {loading && (
          <div style={{ textAlign: 'center', padding: '40px' }}>
            로딩 중...
          </div>
        )}

        {error && (
          <div style={{
            background: '#fed7d7',
            border: '1px solid #fc8181',
            borderRadius: '8px',
            padding: '12px 16px',
            marginBottom: '20px',
            color: '#c53030'
          }}>
            {error}
          </div>
        )}

        <div style={{
          background: 'white',
          borderRadius: '12px',
          border: '1px solid #e2e8f0',
          padding: '24px'
        }}>
          <label style={{ 
            display: 'block', 
            fontSize: '14px', 
            fontWeight: '600', 
            color: '#4a5568',
            marginBottom: '8px'
          }}>
            프로젝트 선택
          </label>
          <select
            value={selectedJobNo}
            onChange={handleSelect}
            style={{
              width: '100%',
              padding: '12px',
              border: '1px solid #e2e8f0',
              borderRadius: '8px',
              fontSize: '14px',
              background: 'white',
              marginBottom: '16px'
            }}
          >
            <option value="">프로젝트를 선택하세요</option>
            {jobs.map(job => (
              <option key={job.job_no} value={job.job_no}>
                {job.job_no} - {job.job_name}
              </option>
            ))}
          </select>

          {selectedJobNo && selectedJobName && (
            <div style={{
              background: '#c6f6d5',
              border: '1px solid #68d391',
              borderRadius: '8px',
              padding: '12px 16px',
              marginBottom: '20px',
              color: '#2f855a',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center'
            }}>
              <div>
                선택된 프로젝트: <strong>{selectedJobNo} - {selectedJobName}</strong>
              </div>
              <button
                onClick={() => {
                  setEditingJobNo(selectedJobNo);
                  setEditedName(selectedJobName);
                }}
                style={{
                  padding: '6px 12px',
                  background: '#48bb78',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  fontSize: '12px',
                  fontWeight: '600'
                }}
                title="프로젝트 이름 수정"
              >
                ✏️ 수정
              </button>
            </div>
          )}
          
          {editingJobNo && (
            <div style={{
              background: '#fff5f5',
              border: '2px solid #fc8181',
              borderRadius: '8px',
              padding: '16px',
              marginBottom: '20px'
            }}>
              <div style={{ marginBottom: '12px', fontWeight: '600', color: '#742a2a' }}>
                프로젝트 이름 수정
              </div>
              <div style={{ display: 'flex', gap: '8px' }}>
                <input
                  type="text"
                  value={editedName}
                  onChange={(e) => setEditedName(e.target.value)}
                  onKeyPress={(e) => {
                    if (e.key === 'Enter') updateJobName(editingJobNo);
                  }}
                  placeholder="새 프로젝트 이름"
                  autoFocus
                  style={{
                    flex: 1,
                    padding: '10px',
                    border: '2px solid #3b82f6',
                    borderRadius: '6px',
                    fontSize: '14px'
                  }}
                />
                <button
                  onClick={() => updateJobName(editingJobNo)}
                  style={{
                    padding: '10px 16px',
                    background: '#10b981',
                    color: 'white',
                    border: 'none',
                    borderRadius: '6px',
                    cursor: 'pointer',
                    fontSize: '14px',
                    fontWeight: '600'
                  }}
                >
                  저장
                </button>
                <button
                  onClick={() => {
                    setEditingJobNo(null);
                    setEditedName('');
                  }}
                  style={{
                    padding: '10px 16px',
                    background: '#ef4444',
                    color: 'white',
                    border: 'none',
                    borderRadius: '6px',
                    cursor: 'pointer',
                    fontSize: '14px',
                    fontWeight: '600'
                  }}
                >
                  취소
                </button>
              </div>
            </div>
          )}

          <button
            onClick={handleConfirm}
            disabled={!selectedJobNo}
            style={{
              width: '100%',
              padding: '12px 24px',
              background: selectedJobNo ? 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' : '#e2e8f0',
              color: selectedJobNo ? 'white' : '#a0aec0',
              border: 'none',
              borderRadius: '8px',
              cursor: selectedJobNo ? 'pointer' : 'not-allowed',
              fontSize: '16px',
              fontWeight: '600'
            }}
          >
            확인
          </button>
        </div>
      </div>
    </div>
  );
};

export default JobSelectionPage;