import { Box, Button, Container, Paper, TextField, Typography, FormControlLabel, Checkbox } from '@mui/material'
import { useState } from 'react'
import api from '../lib/api'
import { useNavigate } from 'react-router-dom'

export default function RegisterCharacter() {
  const [name, setName] = useState('')
  const [server, setServer] = useState('')
  const [job, setJob] = useState('')
  const [power, setPower] = useState('')
  const [isPublic, setIsPublic] = useState(false)
  const navigate = useNavigate()

  const handleSubmit = async () => {
    if (!name) {
      alert('캐릭터명을 입력해주세요.')
      return
    }

    try {
      await api.post('/characters', {
        name,
        server: server || undefined,
        job: job || undefined,
        combat_power: power ? parseInt(power, 10) : undefined,
        is_public: isPublic,
      })
      alert('캐릭터가 성공적으로 등록되었습니다.')
      navigate('/characters')
    } catch (err: any) {
      console.error(err)
      alert('캐릭터 등록 중 오류가 발생했습니다.')
    }
  }

  return (
      <Container maxWidth="sm">
        <Paper sx={{ p: 4, mt: 8 }}>
          <Typography variant="h5" gutterBottom>
            캐릭터 등록
          </Typography>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <TextField
                label="캐릭터명 *"
                value={name}
                onChange={(e) => setName(e.target.value)}
                fullWidth
                required
            />
            <TextField
                label="서버"
                value={server}
                onChange={(e) => setServer(e.target.value)}
                fullWidth
            />
            <TextField
                label="직업"
                value={job}
                onChange={(e) => setJob(e.target.value)}
                fullWidth
            />
            <TextField
                label="전투력"
                type="number"
                value={power}
                onChange={(e) => setPower(e.target.value)}
                fullWidth
            />
            <FormControlLabel
                control={<Checkbox checked={isPublic} onChange={e => setIsPublic(e.target.checked)} />}
                label="친구에게 노출"
            />
            <Button variant="contained" onClick={handleSubmit}>
              등록
            </Button>
          </Box>
        </Paper>
      </Container>
  )
}
