import { useEffect, useState } from 'react'
import { Button, Input, Space, message } from 'antd'
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import Modal from './DraggableModal'

type Props = {
  open: boolean
  items: string[]
  saving?: boolean
  submitClassName?: string
  onCancel: () => void
  onSave: (items: string[]) => void
}

export default function SubjectSettingsModal({
  open,
  items,
  saving,
  submitClassName,
  onCancel,
  onSave }: Props) {
  const [list, setList] = useState<string[]>([])
  const [input, setInput] = useState('')

  useEffect(() => {
    if (!open) return
    setList(items.length ? [...items] : [])
    setInput('')
    // 팝업이 열릴 때만 초기화 (편집 중 items 참조 변경으로 목록이 리셋되지 않도록)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open])

  const addItem = () => {
    const value = input.trim()
    if (!value) {
      message.warning('과목을 입력하세요.')
      return
    }
    if (list.some((item) => item === value)) {
      message.warning('이미 등록된 과목입니다.')
      return
    }
    setList((prev) => [...prev, value])
    setInput('')
  }

  const removeItem = (index: number) => {
    setList((prev) => prev.filter((_, i) => i !== index))
  }

  const handleSave = () => {
    if (!list.length) {
      message.warning('과목을 1개 이상 등록하세요.')
      return
    }
    onSave(list)
  }

  return (
    <Modal
      title="과목설정"
      open={open}
      onCancel={onCancel}
      footer={null}
      destroyOnHidden
      width={420}
    >
      <div className="subject-settings">
        <Space.Compact className="full-width subject-settings-add">
          <Input
            value={input}
            placeholder="과목명 입력"
            maxLength={40}
            onChange={(e) => setInput(e.target.value)}
            onPressEnter={(e) => {
              e.preventDefault()
              addItem()
            }}
          />
          <Button type="primary" icon={<PlusOutlined />} onClick={addItem}>
            추가
          </Button>
        </Space.Compact>

        <ul className="subject-settings-list">
          {list.map((item, index) => (
            <li key={`${item}-${index}`} className="subject-settings-item">
              <span className="subject-settings-name">{item}</span>
              <Button
                type="text"
                danger
                size="small"
                icon={<DeleteOutlined />}
                aria-label={`${item} 삭제`}
                onClick={() => removeItem(index)}
              >
                삭제
              </Button>
            </li>
          ))}
          {!list.length ? (
            <li className="subject-settings-empty">등록된 과목이 없습니다.</li>
          ) : null}
        </ul>

        <div className="balance-modal-footer">
          <Button
            className={submitClassName}
            type="primary"
            loading={saving}
            onClick={handleSave}
          >
            저장
          </Button>
          <Button onClick={onCancel}>취소</Button>
        </div>
      </div>
    </Modal>
  )
}
