import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { createDiscountVoucher } from '../../api/session'

export function DiscountCreatePage() {
  const navigate = useNavigate()
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    const code = String(fd.get('code') ?? '').trim()
    const description = String(fd.get('description') ?? '')
    const discount_type = String(fd.get('discount_type') ?? 'percent')
    const discount_value = Number(fd.get('discount_value'))
    const max_uses_raw = String(fd.get('max_uses') ?? '').trim()
    const valid_from = String(fd.get('valid_from') ?? '').trim()
    const valid_until = String(fd.get('valid_until') ?? '').trim()
    const is_active = fd.get('is_active') === 'on'

    setBusy(true)
    setError(null)
    try {
      await createDiscountVoucher({
        code,
        description,
        discount_type,
        discount_value,
        max_uses: max_uses_raw === '' ? null : Number(max_uses_raw),
        valid_from: valid_from || null,
        valid_until: valid_until || null,
        is_active,
      })
      navigate('/app/administrator/discounts')
    } catch (err: unknown) {
      setError(err instanceof ApiHttpError ? err.message : 'Could not save voucher.')
    } finally {
      setBusy(false)
    }
  }

  function autoGenerateCode() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    let code = ''
    for (let i = 0; i < 10; i++) code += chars.charAt(Math.floor(Math.random() * chars.length))
    const input = document.getElementById('discount_code_input') as HTMLInputElement | null
    if (input) input.value = code
    const desc = document.getElementById('discount_description') as HTMLTextAreaElement | null
    if (desc) {
      desc.value = desc.value.replace(/^Auto-generated on \d{4}-\d{2}-\d{2}\s*[—-]\s*reason:\s*/i, '')
    }
  }

  return (
    <div className="container mt-4">
      <h1>Create Discount Voucher</h1>

      {error ? <div className="alert alert-danger">{error}</div> : null}

      <form method="post" onSubmit={onSubmit}>
        <div className="mb-3">
          <label className="form-label" htmlFor="discount_code_input">
            Voucher Code
          </label>
          <div className="input-group">
            <input
              type="text"
              name="code"
              id="discount_code_input"
              className="form-control"
              placeholder="Enter or generate a code (e.g. WELCOME10)"
              required
            />
            <button type="button" className="btn btn-outline-secondary" onClick={autoGenerateCode}>
              Auto Generate
            </button>
          </div>
        </div>

        <div className="mb-3">
          <label className="form-label" htmlFor="discount_description">
            Description / Reason
          </label>
          <textarea
            name="description"
            id="discount_description"
            className="form-control"
            rows={3}
            placeholder="Reason for this voucher."
          />
          <div className="form-text">Visible to admins only; not shown to parents.</div>
        </div>

        <div className="mb-3">
          <label className="form-label" htmlFor="discount_type">
            Discount Type
          </label>
          <select name="discount_type" id="discount_type" className="form-select" required>
            <option value="percent">Percentage (%)</option>
            <option value="fixed">Fixed Amount ($)</option>
          </select>
        </div>

        <div className="mb-3">
          <label className="form-label" htmlFor="discount_value">
            Discount Value
          </label>
          <input
            type="number"
            name="discount_value"
            id="discount_value"
            className="form-control"
            step="0.01"
            min="0"
            placeholder="e.g. 10 for 10% or 50 for $50"
            required
          />
        </div>

        <div className="mb-3">
          <label className="form-label" htmlFor="max_uses">
            Maximum Uses
          </label>
          <input
            type="number"
            name="max_uses"
            id="max_uses"
            className="form-control"
            placeholder="Leave empty for unlimited"
          />
        </div>

        <div className="mb-3">
          <label className="form-label" htmlFor="valid_from">
            Valid From
          </label>
          <input type="date" name="valid_from" id="valid_from" className="form-control" />
        </div>

        <div className="mb-3">
          <label className="form-label" htmlFor="valid_until">
            Valid Until
          </label>
          <input type="date" name="valid_until" id="valid_until" className="form-control" />
        </div>

        <div className="form-check mb-3">
          <input
            type="checkbox"
            name="is_active"
            id="is_active"
            className="form-check-input"
            defaultChecked
          />
          <label className="form-check-label" htmlFor="is_active">
            Active
          </label>
        </div>

        <button type="submit" className="btn btn-success" disabled={busy}>
          Save Voucher
        </button>
        <Link to="/app/administrator/discounts" className="btn btn-info ms-2">
          Cancel
        </Link>
      </form>
    </div>
  )
}
