import { type FormEvent, useEffect, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { useSchoolYearOptions } from '../../hooks/useSchoolYearOptions'
import {
  downloadFinancialSummaryPdf,
  fetchFinancialReportSummary,
  type FinancialSummaryJson,
} from '../../api/paymentManagement'

function fmt(n: unknown): string {
  return `$${Number(n || 0).toFixed(2)}`
}

export function FinancialReportSummaryPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const urlYear = searchParams.get('school_year') ?? ''

  const [schoolYear, setSchoolYear] = useState(urlYear)
  const [d, setD] = useState<FinancialSummaryJson | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const { options, selectedYear } = useSchoolYearOptions({
    preferredYear: schoolYear || urlYear,
  })

  function load(y: string) {
    setLoading(true)
    setError(null)
    fetchFinancialReportSummary({ school_year: y || undefined })
      .then(setD)
      .catch((e: unknown) =>
        setError(e instanceof ApiHttpError ? e.message : 'Could not load summary.'),
      )
      .finally(() => setLoading(false))
  }

  useEffect(() => {
    setSchoolYear(urlYear)
    load(urlYear)
  }, [urlYear])

  function onYearSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    const y = String(fd.get('school_year') ?? '')
    const next = new URLSearchParams()
    if (y) next.set('school_year', y)
    setSearchParams(next)
  }

  async function onPdf() {
    try {
      await downloadFinancialSummaryPdf({ school_year: schoolYear || undefined })
    } catch (e: unknown) {
      setError(e instanceof ApiHttpError ? e.message : 'PDF download failed.')
    }
  }

  const labels = [
    { key: 'sumCharges', label: 'Total Charges', val: d?.totalCharges },
    { key: 'sumEventFees', label: 'Event Fees', val: d?.totalEventFees },
    { key: 'sumExtraCharges', label: 'Total Extra Charges', val: d?.totalExtraCharges },
    { key: 'sumDiscounts', label: 'Total Discounts', val: d?.totalDiscounts },
    { key: 'sumRefunds', label: 'Total Refunds', val: d?.totalRefunds },
    { key: 'sumExpenses', label: 'Total Expenses', val: d?.totalExpenses },
    { key: 'sumReimb', label: 'Total Reimbursements', val: d?.totalReimbursements },
    {
      key: 'sumDonationToSchool',
      label: 'Donation to School (Masjid & Donation)',
      val: d?.donationToSchool,
    },
  ]

  const barItems = [
    { label: 'Charges', val: Number(d?.totalCharges ?? 0), color: '#007bff' },
    { label: 'Paid', val: Number(d?.amountCollected ?? d?.totalPaid ?? 0), color: '#28a745' },
    { label: 'Unpaid', val: Number(d?.totalUnpaid ?? 0), color: '#ffc107' },
    { label: 'Net', val: Number(d?.netAmount ?? 0), color: '#20c997' },
  ]
  const barMax = Math.max(1, ...barItems.map((b) => b.val))

  return (
    <div className="container-fluid mt-4">
      <h2 className="text-center mt-4 mb-3">Financial Report Summary</h2>

      <div className="d-flex align-items-center gap-2 my-3 flex-nowrap w-100 overflow-auto" style={{ whiteSpace: 'nowrap' }}>
        <form id="summaryYearFilter" className="d-flex align-items-center gap-2 flex-nowrap me-auto" onSubmit={onYearSubmit}>
          <label className="form-label mb-0 me-2">School year</label>
          <select
            name="school_year"
            className="form-select form-select-sm rounded-pill px-3"
            style={{ minWidth: 180 }}
            value={schoolYear || selectedYear}
            onChange={(e) => {
              const y = e.target.value
              setSchoolYear(y)
              const next = new URLSearchParams()
              if (y) next.set('school_year', y)
              setSearchParams(next)
            }}
          >
            {(options.length > 0 ? options : [{ value: selectedYear, label: selectedYear }]).map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </form>
        <div className="d-flex align-items-center gap-2 flex-nowrap flex-shrink-0">
          <button type="button" className="btn btn-primary" onClick={onPdf}>
            Download PDF
          </button>
          <Link className="btn btn-secondary" to="/app/administrator/payment/financial-report">
            Back To Detailed Report
          </Link>
        </div>
      </div>

      <p className="text-muted">Report for School Year: {d?.schoolYear ?? schoolYear}</p>

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

      <div className="table-responsive">
        <table className="table w-100">
          <thead>
            <tr>
              <th>Description</th>
              <th className="text-end">Amount</th>
            </tr>
          </thead>
          <tbody>
            {labels.map((row) => (
              <tr key={row.key}>
                <td>{row.label}</td>
                <td className="text-end">{fmt(row.val)}</td>
              </tr>
            ))}
            <tr className="table-success">
              <td className="fw-bold">Net Amount (Earned Income)</td>
              <td className="text-end fw-bold">{fmt(d?.netAmount)}</td>
            </tr>
            <tr className="table-info">
              <td className="fw-bold">Amount Collected (Paid)</td>
              <td className="text-end fw-bold">{fmt(d?.amountCollected)}</td>
            </tr>
            <tr className="table-warning">
              <td className="fw-bold">Amount Unpaid (Outstanding)</td>
              <td className="text-end fw-bold">{fmt(d?.totalUnpaid)}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <div className="my-4">
        <h3>Summary overview</h3>
        <p className="text-muted small">
          Chart.js is not bundled in this SPA; relative bars below mirror the legacy dashboard.
        </p>
        <div className="d-flex flex-column gap-2" style={{ maxWidth: 560 }}>
          {barItems.map((b) => (
            <div key={b.label}>
              <div className="d-flex justify-content-between small mb-1">
                <span>{b.label}</span>
                <span>{fmt(b.val)}</span>
              </div>
              <div className="progress" style={{ height: 10 }}>
                <div
                  className="progress-bar"
                  style={{
                    width: `${(b.val / barMax) * 100}%`,
                    backgroundColor: b.color,
                  }}
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
