import { ArrowLeft, ArrowRight } from 'lucide-react'
import { FormEvent, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { api } from '../api'

export function NewCourse() {
  const navigate = useNavigate()
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState('')

  async function submit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setBusy(true)
    const f = new FormData(e.currentTarget)
    try {
      const { course } = await api.createCourse({
        name: String(f.get('name')),
        category: String(f.get('category')),
        audience: '',
        description: String(f.get('description')),
      })
      navigate(`/courses/${course.id}`)
    } catch (x) {
      setError((x as Error).message)
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="page form-page">
      <Link to="/" className="back-link">
        <ArrowLeft size={16} />返回课程
      </Link>
      <div className="form-layout">
        <aside>
          <span className="step-number">01</span>
          <p className="eyebrow">创建课程</p>
          <h1>
            先告诉我们，<br />
            这是一门什么课。
          </h1>
          <p>填写基本信息后，可添加课程资产和讲师，也可以直接跳过。</p>
        </aside>
        <form className="paper-form" onSubmit={submit}>
          <div className="form-title">
            <span>COURSE PROFILE</span>
            <h2>课程基本信息</h2>
          </div>
          <label>
            课程名称 <b>*</b>
            <input name="name" required maxLength={100} />
          </label>
          <label>
            课程分类
            <select name="category" defaultValue="党政专题">
              <option>党政专题</option>
              <option>高校公开课</option>
              <option>企业培训</option>
              <option>职业教育</option>
              <option>其他</option>
            </select>
          </label>
          <label>
            课程简介
            <textarea name="description" rows={4} maxLength={500} />
          </label>
          {error && <p className="form-error">{error}</p>}
          <div className="form-footer">
            <span>下一步：课程资产与讲师</span>
            <button className="primary-button" disabled={busy}>
              {busy ? '正在创建…' : '继续'}
              <ArrowRight size={17} />
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
