import React, { useState } from 'react';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import Box from '@mui/material/Box';
import api from '../../api';

export default function CreateProjectDialog({ open, onClose, onCreated }) {
  const [code, setCode] = useState('');
  const [name, setName] = useState('');
  const [client, setClient] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    if (!code.trim() || !name.trim()) return;
    setSubmitting(true);
    try {
      await api.post('/dashboard/projects', null, {
        params: {
          official_project_code: code.trim(),
          project_name: name.trim(),
          client_name: client.trim() || undefined,
        },
      });
      setCode('');
      setName('');
      setClient('');
      onCreated?.();
      onClose();
    } catch (err) {
      alert(err.response?.data?.detail || '프로젝트 생성 실패');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle sx={{ fontWeight: 700 }}>프로젝트 생성</DialogTitle>
      <DialogContent>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
          <TextField
            label="프로젝트 코드"
            placeholder="예: J24-001"
            value={code}
            onChange={e => setCode(e.target.value)}
            size="small"
            required
            fullWidth
          />
          <TextField
            label="프로젝트명"
            placeholder="예: 울산 SK에너지 확장"
            value={name}
            onChange={e => setName(e.target.value)}
            size="small"
            required
            fullWidth
          />
          <TextField
            label="고객사 (선택)"
            placeholder="예: Samsung Engineering"
            value={client}
            onChange={e => setClient(e.target.value)}
            size="small"
            fullWidth
          />
        </Box>
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        <Button onClick={onClose} color="inherit">취소</Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
          disabled={submitting || !code.trim() || !name.trim()}
        >
          생성
        </Button>
      </DialogActions>
    </Dialog>
  );
}
