import { type FormEvent, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { applyDiscountByCodeForStudent } from '../../api/paymentManagement'

/** Mini form from CI `payment/discount.php` — apply voucher code for a single student. */
export function PaymentDiscountStudentPage() {
  const [searchParams] = useSearchParams()
  const studentId = searchParams.get('student_id') ?? ''
  const [code, setCode] = useState('')
  const [msg, setMsg] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    if (!studentId || !code.trim()) {
      setMsg('Student and voucher code are required.')
      return
    }
    setBusy(true)
    setMsg(null)
    try {
      await applyDiscountByCodeForStudent({ student_id: studentId, voucher_code: code.trim() })
      setMsg('Voucher applied.')
      setCode('')
    } catch (err: unknown) {
      setMsg(err instanceof ApiHttpError ? err.message : 'Apply failed.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="container py-4" style={{ maxWidth: 480 }}>
      <h1 className="h5 mb-3">Apply voucher</h1>
      {!studentId ? (
        <div className="alert alert-warning">Missing student_id in URL query.</div>
      ) : (
        <p className="text-muted small mb-3">
          Student ID: <strong>{studentId}</strong>
        </p>
      )}
      {msg ? (
        <div
          className={`alert ${msg.includes('fail') || msg.includes('Missing') ? 'alert-warning' : 'alert-success'}`}
        >
          {msg}
        </div>
      ) : null}
      <form onSubmit={onSubmit}>
        <div className="input-group mb-3">
          <input
            type="text"
            name="voucher_code"
            className="form-control"
            placeholder="Enter Voucher Code"
            required
            value={code}
            onChange={(e) => setCode(e.target.value)}
            disabled={!studentId}
          />
          <button className="btn btn-primary" type="submit" disabled={busy || !studentId}>
            Apply
          </button>
        </div>
      </form>
    </div>
  )
}
