import { type FormEvent, useEffect, useState } from 'react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { createExpense, fetchExpenseCreateForm } from '../../api/session'
import type { ExpenseUserOption } from '../../api/types'
import { EXPENSE_CATEGORIES, expensePurchasedByValue } from './expenseUtils'
import { ExpenseVendorFields } from './ExpenseVendorFields'

export function ExpenseCreatePage() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const schoolYear = searchParams.get('school_year') ?? ''
  const semester = searchParams.get('semester') ?? ''

  const [retailors, setRetailors] = useState<string[]>([])
  const [users, setUsers] = useState<ExpenseUserOption[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    let cancelled = false
    fetchExpenseCreateForm()
      .then((d) => {
        if (!cancelled) {
          setRetailors(d.retailors ?? [])
          setUsers(d.users ?? [])
          setError(null)
        }
      })
      .catch((e: unknown) => {
        if (!cancelled)
          setError(e instanceof ApiHttpError ? e.message : 'Could not load form options.')
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })
    return () => {
      cancelled = true
    }
  }, [])

  const listQs = searchParams.toString()
  const cancelHref = listQs
    ? `/app/administrator/expenses?${listQs}`
    : '/app/administrator/expenses'

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setSubmitting(true)
    setError(null)
    const fd = new FormData(e.currentTarget)
    if (schoolYear) fd.set('school_year', schoolYear)
    if (semester) fd.set('semester', semester)
    try {
      await createExpense(fd)
      navigate(cancelHref)
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Submit failed.')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="container mt-4">
      <h1>Add Expense / Purchase</h1>

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

      {!loading && (
        <form onSubmit={onSubmit} encType="multipart/form-data">
          <div className="mb-3">
            <label className="form-label">Category</label>
            <select name="category" className="form-control form-select" required defaultValue="Expense">
              {EXPENSE_CATEGORIES.map((c) => (
                <option key={c} value={c}>
                  {c === 'Donation' ? 'Donation (non-reimbursable)' : c}
                </option>
              ))}
            </select>
            <div className="form-text text-muted">
              Use Donation when someone gifts items to the school so it is counted as an expense but skipped
              from reimbursement queues.
            </div>
          </div>

          <div className="mb-3">
            <label className="form-label">Amount</label>
            <input type="number" step="0.01" name="amount" className="form-control" required />
          </div>

          <div className="mb-3">
            <label className="form-label">Vendor</label>
            <ExpenseVendorFields retailors={retailors} initialRetailor="" />
          </div>

          <div className="mb-3">
            <label className="form-label">Purchased By</label>
            <select name="purchased_by" className="form-control form-select" required defaultValue="">
              <option value="">-- Select --</option>
              {users.map((u) => (
                <option key={u.id} value={expensePurchasedByValue(u)}>
                  {`${String(u.firstname ?? '').trim()} ${String(u.lastname ?? '').trim()}`.trim()}
                </option>
              ))}
            </select>
          </div>

          <div className="mb-3">
            <label className="form-label">Date of Purchase</label>
            <input type="date" name="date_of_purchase" className="form-control" />
          </div>

          <div className="mb-3">
            <label className="form-label">Description</label>
            <textarea name="description" className="form-control" rows={4} />
          </div>

          <div className="mb-3">
            <label className="form-label">Receipt Image</label>
            <input type="file" name="receipt" className="form-control" accept=".jpg,.jpeg,.png,.webp,.gif,.pdf" required />
          </div>

          <button type="submit" className="btn btn-primary" disabled={submitting}>
            {submitting ? 'Submitting…' : 'Submit'}
          </button>
          <Link to={cancelHref} className="btn btn-secondary ms-2">
            Cancel
          </Link>
        </form>
      )}
    </div>
  )
}
