import { useEffect, useState, type FormEvent } from 'react'
import { finance } from '@/api/client'
import type { Account } from '@/types/api'
import { PageHeader } from '@/components/PageHeader'
import { Loading } from '@/components/Loading'
import { ErrorBox } from '@/components/ErrorBox'
import { DataTable, type Column } from '@/components/DataTable'

const ACCOUNT_TYPES = ['ASSET', 'LIABILITY', 'EQUITY', 'REVENUE', 'EXPENSE'] as const

export function AccountsPage() {
  const [rows, setRows] = useState<Account[]>([])
  const [error, setError] = useState<Error | null>(null)
  const [loading, setLoading] = useState(true)
  const [showCreate, setShowCreate] = useState(false)
  const [code, setCode] = useState('')
  const [name, setName] = useState('')
  const [accountType, setAccountType] = useState<string>('ASSET')
  const [creating, setCreating] = useState(false)

  const load = () => {
    finance
      .listAccounts()
      .then((rs) => setRows([...rs].sort((a, b) => a.code.localeCompare(b.code))))
      .catch((e: unknown) => setError(e instanceof Error ? e : new Error(String(e))))
      .finally(() => setLoading(false))
  }

  useEffect(() => { load() }, []) // eslint-disable-line react-hooks/exhaustive-deps

  const onCreate = async (e: FormEvent) => {
    e.preventDefault()
    setCreating(true)
    setError(null)
    try {
      await finance.createAccount({ code, name, accountType })
      setCode('')
      setName('')
      setShowCreate(false)
      load()
    } catch (err: unknown) {
      setError(err instanceof Error ? err : new Error(String(err)))
    } finally {
      setCreating(false)
    }
  }

  const columns: Column<Account>[] = [
    { header: 'Code', key: 'code', render: (r) => <span className="font-mono">{r.code}</span> },
    { header: 'Name', key: 'name' },
    { header: 'Type', key: 'accountType' },
    { header: 'Description', key: 'description', render: (r) => r.description ?? '—' },
  ]

  return (
    <div>
      <PageHeader
        title="Chart of Accounts"
        subtitle="GL accounts that journal entries debit and credit. 6 accounts seeded by default."
        actions={
          <button className="btn-primary" onClick={() => setShowCreate(!showCreate)}>
            {showCreate ? 'Cancel' : '+ New Account'}
          </button>
        }
      />
      {showCreate && (
        <form onSubmit={onCreate} className="card p-4 mb-4 max-w-2xl flex flex-wrap items-end gap-3">
          <div className="w-24">
            <label className="block text-xs font-medium text-slate-700">Code</label>
            <input type="text" required value={code} onChange={(e) => setCode(e.target.value)}
              placeholder="1300" className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1.5 text-sm" />
          </div>
          <div className="flex-1 min-w-[150px]">
            <label className="block text-xs font-medium text-slate-700">Name</label>
            <input type="text" required value={name} onChange={(e) => setName(e.target.value)}
              placeholder="Prepaid expenses" className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1.5 text-sm" />
          </div>
          <div className="w-32">
            <label className="block text-xs font-medium text-slate-700">Type</label>
            <select value={accountType} onChange={(e) => setAccountType(e.target.value)}
              className="mt-1 w-full rounded-md border border-slate-300 px-2 py-1.5 text-sm">
              {ACCOUNT_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
            </select>
          </div>
          <button type="submit" className="btn-primary" disabled={creating}>
            {creating ? '...' : 'Create'}
          </button>
        </form>
      )}
      {loading && <Loading />}
      {error && <ErrorBox error={error} />}
      {!loading && !error && <DataTable rows={rows} columns={columns} />}
    </div>
  )
}
