import { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchDiscountsList } from '../../api/session'
import type { DiscountVoucherRow } from '../../api/types'
import { AcademicFilterBar } from './AcademicFilterBar'

function formatValidityDate(value?: string | null) {
  if (value == null || String(value).trim() === '') return 'N/A'
  const s = String(value)
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s)
  if (m) return `${m[2]}-${m[3]}-${m[1]}`
  const d = new Date(s)
  return Number.isNaN(d.getTime()) ? s : d.toLocaleDateString()
}

export function DiscountListPage() {
  const [searchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? undefined
  const semester = searchParams.get('semester') ?? undefined

  const [vouchers, setVouchers] = useState<DiscountVoucherRow[]>([])
  const [schoolYears, setSchoolYears] = useState<string[] | undefined>(undefined)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    fetchDiscountsList({ school_year: schoolYear, semester })
      .then((d) => {
        if (cancelled) return
        setVouchers(d.vouchers ?? [])
        setSchoolYears(d.school_years)
      })
      .catch((e: unknown) => {
        if (!cancelled)
          setError(e instanceof ApiHttpError ? e.message : 'Could not load discounts.')
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })
    return () => {
      cancelled = true
    }
  }, [schoolYear, semester])

  return (
    <div className="container-fluid mt-4">
      <h2 className="text-center mt-4 mb-3">Discounts</h2>
      <AcademicFilterBar schoolYears={schoolYears} />

      <div className="d-flex gap-2 mb-3 justify-content-end">
        <Link to="/app/administrator/discounts/create" className="btn btn-primary">
          Create New Voucher
        </Link>
        <Link to="/app/administrator/discounts/apply" className="btn btn-success">
          Apply Voucher to Parents
        </Link>
        <Link to="/app/administrator/discounts/reverse" className="btn btn-outline-warning">
          Reverse Discount
        </Link>
      </div>

      {loading ? (
        <p className="text-muted">Loading…</p>
      ) : error ? (
        <div className="alert alert-danger">{error}</div>
      ) : null}

      <div className="table-responsive">
        <table className="table table-striped w-100">
          <thead>
            <tr>
              <th>Code</th>
              <th>Type</th>
              <th>Value</th>
              <th>Max Uses</th>
              <th>Times Used</th>
              <th>Validity</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {vouchers.map((v) => (
              <tr key={String(v.id)}>
                <td>{v.code}</td>
                <td>{String(v.discount_type).charAt(0).toUpperCase() + String(v.discount_type).slice(1)}</td>
                <td>
                  {v.discount_type === 'percent'
                    ? `${v.discount_value}%`
                    : `$${Number(v.discount_value).toFixed(2)}`}
                </td>
                <td>{v.max_uses != null && v.max_uses !== '' ? String(v.max_uses) : '∞'}</td>
                <td>{v.times_used != null ? String(v.times_used) : '—'}</td>
                <td>
                  {formatValidityDate(v.valid_from)} → {formatValidityDate(v.valid_until)}
                </td>
                <td>
                  <span className={`badge ${v.is_active ? 'bg-success' : 'bg-secondary'}`}>
                    {v.is_active ? 'Active' : 'Inactive'}
                  </span>
                </td>
                <td>
                  <span className="text-muted small">Edit (API)</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
