import { type FormEvent, useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchReimbursementForEdit, updateReimbursement } from '../../api/reimbursements'

export function ReimbursementEditPage() {
  const { reimbursementId } = useParams<{ reimbursementId: string }>()
  const id = reimbursementId ?? ''

  const [users, setUsers] = useState<Array<{ id?: number | string; firstname?: string; lastname?: string }>>([])
  const [reimb, setReimb] = useState<Record<string, unknown> | null>(null)
  const [receiptUrl, setReceiptUrl] = useState<string | null>(null)
  const [method, setMethod] = useState('')
  const [loading, setLoading] = useState(true)
  const [msg, setMsg] = useState<string | null>(null)

  useEffect(() => {
    if (!id) return
    setLoading(true)
    fetchReimbursementForEdit(id)
      .then((d) => {
        setUsers(d.users ?? [])
        setReimb(d.reimbursement ?? null)
        setReceiptUrl(d.receipt_url ?? null)
        setMethod(String(d.reimbursement?.reimbursement_method ?? ''))
      })
      .catch(() => setMsg('Could not load reimbursement.'))
      .finally(() => setLoading(false))
  }, [id])

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    setMsg(null)
    try {
      await updateReimbursement(id, fd)
      setMsg('Saved.')
    } catch (err: unknown) {
      setMsg(err instanceof ApiHttpError ? err.message : 'Update failed.')
    }
  }

  if (!id) {
    return <div className="container mt-4">Missing reimbursement id.</div>
  }

  if (loading || !reimb) {
    return (
      <div className="container mt-4">
        <p className="text-muted">{loading ? 'Loading…' : 'Not found.'}</p>
      </div>
    )
  }

  const rid = reimb.id
  const isCheck = method === 'Check'
  const recipient = String(reimb.reimbursed_to ?? '')
  const amount = reimb.amount
  const checkNum = String(reimb.check_number ?? '')
  const desc = String(reimb.description ?? '')
  const hasReceiptPath = Boolean(reimb.receipt_path)

  return (
    <div className="container mt-4">
      <h2>Edit Reimbursement #{String(rid ?? '')}</h2>

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

      <form method="post" encType="multipart/form-data" onSubmit={onSubmit}>
        <div className="mb-3">
          <label className="form-label">Amount</label>
          <input
            type="number"
            step={0.01}
            name="amount"
            className="form-control"
            required
            defaultValue={typeof amount === 'number' ? amount : String(amount ?? '')}
          />
        </div>

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

        <div className="mb-3" style={{ display: isCheck ? '' : 'none' }}>
          <label className="form-label">Check Number</label>
          <input type="text" name="check_number" className="form-control" defaultValue={checkNum} />
        </div>

        <div className="mb-3">
          <label className="form-label">Receipt (optional to replace)</label>
          {receiptUrl ? (
            <div className="mb-2">
              <a href={receiptUrl} target="_blank" rel="noopener noreferrer">
                Current receipt
              </a>
            </div>
          ) : null}
          <input type="file" name="receipt" className="form-control" accept=".jpg,.jpeg,.png,.webp,.gif,.pdf" />
          {hasReceiptPath ? (
            <div className="form-check mt-2">
              <input className="form-check-input" type="checkbox" name="remove_receipt" value="1" id="rmr" />
              <label className="form-check-label" htmlFor="rmr">
                Remove existing receipt
              </label>
            </div>
          ) : null}
        </div>

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

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