import { useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { apiUrl } from '../../lib/apiOrigin'
import { fetchExpensesList, updateExpenseStatus } from '../../api/session'
import type { ExpenseRow } from '../../api/types'
import { AcademicFilterBar } from '../discounts/AcademicFilterBar'
import {
  formatCreatedAt,
  formatMoney,
  purchaseDateDisplay,
  totalExpenseAmount,
  vendorDisplay,
} from './expenseUtils'

function receiptHref(row: ExpenseRow): string | null {
  if (row.receipt_url) return row.receipt_url
  const p = row.receipt_path
  if (!p) return null
  const path = String(p).replace(/^\/+/, '')
  return apiUrl(`/receipts/${path}`)
}

function isDonation(row: ExpenseRow): boolean {
  return String(row.category ?? '').toLowerCase() === 'donation'
}

function statusBadgeClass(status: string): string {
  const s = String(status).toLowerCase()
  if (s === 'approved') return 'success'
  if (s === 'denied') return 'danger'
  return 'secondary'
}

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

  const [rows, setRows] = useState<ExpenseRow[]>([])
  const [schoolYears, setSchoolYears] = useState<string[] | undefined>(undefined)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [flash, setFlash] = useState<string | null>(null)

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

  async function handleExpenseAction(id: number, status: 'approved' | 'denied') {
    if (!window.confirm(`Are you sure you want to ${status} this expense?`)) return
    try {
      const res = await updateExpenseStatus({ id, status })
      const body = res as { success?: boolean; error?: string }
      if (body.success === false || body.error) {
        setFlash(body.error ?? 'Action failed.')
        return
      }
      setFlash(null)
      setLoading(true)
      fetchExpensesList({ school_year: schoolYear, semester })
        .then((d) => {
          setRows(d.expenses ?? [])
          setSchoolYears(d.school_years)
        })
        .finally(() => setLoading(false))
    } catch (e: unknown) {
      setFlash(e instanceof ApiHttpError ? e.message : 'Server error.')
    }
  }

  const total = totalExpenseAmount(rows)

  const createLink = filterQs
    ? `/app/administrator/expenses/create?${filterQs}`
    : '/app/administrator/expenses/create'

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

      <div className="d-flex gap-2 mb-3 justify-content-end">
        <Link to={createLink} className="btn btn-success mb-3">
          Add New
        </Link>
      </div>

      {flash ? (
        <div className="alert alert-warning" role="alert">
          {flash}
        </div>
      ) : null}

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

      <div className="table-responsive">
        <table
          className="table table-bordered table-striped align-middle w-100 no-mgmt-sticky"
          style={{ tableLayout: 'auto' }}
        >
          <thead className="table-light">
            <tr>
              <th>Category</th>
              <th>Amount</th>
              <th>Vendor</th>
              <th>Purchased By</th>
              <th>Date of Purchase</th>
              <th>Description</th>
              <th>Status</th>
              <th>Approved By</th>
              <th>Receipt</th>
              <th>Added On</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((e) => {
              const href = receiptHref(e)
              const purchaser = [e.purchaser_firstname, e.purchaser_lastname]
                .filter(Boolean)
                .join(' ')
                .trim()
              const approver = [e.approver_firstname, e.approver_lastname]
                .filter(Boolean)
                .join(' ')
                .trim()
              const donation = isDonation(e)
              return (
                <tr key={e.id}>
                  <td>
                    {e.category}
                    {donation ? (
                      <span className="badge bg-info text-dark ms-1">Non-reimbursable</span>
                    ) : null}
                  </td>
                  <td>{formatMoney(e.amount)}</td>
                  <td>{vendorDisplay(e)}</td>
                  <td>{purchaser || 'N/A'}</td>
                  <td>{purchaseDateDisplay(e)}</td>
                  <td>{e.description ?? ''}</td>
                  <td>
                    <span className={`badge bg-${statusBadgeClass(e.status)}`}>
                      {e.status ? e.status.charAt(0).toUpperCase() + e.status.slice(1).toLowerCase() : '—'}
                    </span>
                    {donation ? (
                      <span className="badge bg-info text-dark ms-1">Donation</span>
                    ) : null}
                  </td>
                  <td>{approver || '—'}</td>
                  <td>
                    {href ? (
                      <a href={href} target="_blank" rel="noreferrer">
                        View receipt
                      </a>
                    ) : (
                      'N/A'
                    )}
                  </td>
                  <td>{formatCreatedAt(e.created_at)}</td>
                  <td className="d-flex gap-2 flex-wrap">
                    <Link
                      className="btn btn-outline-secondary btn-sm"
                      to={`/app/administrator/expenses/${e.id}/edit${filterQs ? `?${filterQs}` : ''}`}
                    >
                      Edit
                    </Link>
                    {donation ? (
                      <span className="text-muted small align-self-center">
                        Donation – no reimbursement actions
                      </span>
                    ) : String(e.status).toLowerCase() === 'pending' ? (
                      <>
                        <button
                          type="button"
                          className="btn btn-success btn-sm"
                          onClick={() => void handleExpenseAction(e.id, 'approved')}
                        >
                          Approve
                        </button>
                        <button
                          type="button"
                          className="btn btn-danger btn-sm"
                          onClick={() => void handleExpenseAction(e.id, 'denied')}
                        >
                          Deny
                        </button>
                      </>
                    ) : null}
                  </td>
                </tr>
              )
            })}
          </tbody>
          <tfoot className="table-light">
            <tr>
              <th>Total</th>
              <th>{formatMoney(total)}</th>
              <th />
              <th />
              <th />
              <th />
              <th />
              <th />
              <th />
              <th />
              <th />
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  )
}
