import { type FormEvent, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { createReimbursement, fetchReimbursementCreateContext } from '../../api/reimbursements'

export function ReimbursementCreatePage() {
  const [searchParams] = useSearchParams()
  const expenseId = searchParams.get('expense_id') ?? ''

  const [users, setUsers] = useState<Array<{ id?: number | string; firstname?: string; lastname?: string }>>([])
  const [method, setMethod] = useState('')
  const [msg, setMsg] = useState<string | null>(null)

  useEffect(() => {
    fetchReimbursementCreateContext({ expense_id: expenseId || undefined })
      .then((d) => setUsers(d.users ?? []))
      .catch(() => {})
  }, [expenseId])

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const form = e.currentTarget
    const fd = new FormData(form)
    if (expenseId) fd.set('expense_id', expenseId)
    setMsg(null)
    try {
      await createReimbursement(fd)
      setMsg('Reimbursement saved.')
      form.reset()
      setMethod('')
    } catch (err: unknown) {
      setMsg(err instanceof ApiHttpError ? err.message : 'Submit failed.')
    }
  }

  const isCheck = method === 'Check'

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

      {msg ? <div className="alert alert-info">{msg}</div> : null}

      <form method="post" encType="multipart/form-data" onSubmit={onSubmit}>
        <input type="hidden" name="expense_id" value={expenseId} />

        <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">Reimbursed To</label>
          <select name="reimbursed_to" className="form-control" required defaultValue="">
            <option value="">-- Select Person --</option>
            {users.map((u) => {
              const id = String(u.id ?? '')
              const label = `${u.firstname ?? ''} ${u.lastname ?? ''}`.trim() || 'Unknown'
              return (
                <option key={id} value={id}>
                  {label}
                </option>
              )
            })}
          </select>
        </div>

        <div className="mb-3">
          <label className="form-label">Reimbursement Method</label>
          <select
            name="reimbursement_method"
            id="reimbursement_method"
            className="form-control"
            required
            value={method}
            onChange={(e) => setMethod(e.target.value)}
          >
            <option value="">-- Select Method --</option>
            <option value="Cash">Cash</option>
            <option value="Check">Check</option>
          </select>
        </div>

        <div className={`mb-3 ${isCheck ? '' : 'd-none'}`}>
          <label className="form-label">Check Number</label>
          <input type="text" name="check_number" className="form-control" />
        </div>

        <div className={`mb-3 ${isCheck ? '' : 'd-none'}`}>
          <label className="form-label">Check Receipt Image</label>
          <input type="file" name="receipt" className="form-control" />
        </div>

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

        <button type="submit" className="btn btn-primary">
          Submit
        </button>
        <Link to="/app/administrator/reimbursements" className="btn btn-secondary ms-2">
          Cancel
        </Link>
      </form>
    </div>
  )
}
