"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { ArrowLeft, Scale } from "lucide-react"

import { reportsApi } from "@/lib/api/general-ledger"
import { errorMessage } from "@/lib/error-map"
import { formatAmount, formatReportDate, todayIso } from "@/lib/format"
import { cn } from "@/lib/utils"
import { ReportType, TrialBalanceRow } from "@/types/general-ledger"

import { buttonVariants } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { DownloadCsvButton } from "@/components/reports/DownloadCsvButton"
import { DownloadPdfButton } from "@/components/reports/DownloadPdfButton"
import { ReportHeader } from "@/components/reports/ReportHeader"

export default function TrialBalancePage() {
  const [asOfDate, setAsOfDate] = useState(todayIso())
  const [rows, setRows] = useState<TrialBalanceRow[] | null>(null)
  const [error, setError] = useState<string | null>(null)

  // Clears stale results the instant asOfDate changes, during the render that reacts to it —
  // not inside the effect below, which would be a synchronous setState-in-effect
  // (react-hooks/set-state-in-effect); this is React's own sanctioned "adjust state during
  // render" pattern instead.
  const [loadedFor, setLoadedFor] = useState<string | null>(null)
  if (loadedFor !== asOfDate) {
    setLoadedFor(asOfDate)
    setRows(null)
    setError(null)
  }

  useEffect(() => {
    if (!asOfDate) return
    let cancelled = false
    reportsApi
      .trialBalance(asOfDate)
      .then((res) => {
        if (!cancelled) setRows(res)
      })
      .catch((err) => {
        if (!cancelled) setError(errorMessage(err))
      })
    return () => {
      cancelled = true
    }
  }, [asOfDate])

  const totalDebit = (rows ?? []).reduce((sum, r) => sum + r.debit, 0)
  const totalCredit = (rows ?? []).reduce((sum, r) => sum + r.credit, 0)

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <Link href="/dashboard/ledgers" className={cn(buttonVariants({ variant: "ghost", size: "icon-lg" }))}>
          <ArrowLeft className="size-5" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-foreground">Trial Balance</h1>
          <p className="text-base text-muted-foreground">Every postable account&apos;s balance as at a date.</p>
        </div>
      </div>

      <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
        <div className="flex flex-col gap-1.5">
          <Label className="text-base">As at</Label>
          <Input type="date" value={asOfDate} onChange={(e) => setAsOfDate(e.target.value)} className="h-11 w-full text-base sm:w-60" />
        </div>
        <div className="flex gap-2">
          <DownloadPdfButton reportType={ReportType.TrialBalance} params={{ asOfDate }} disabled={!rows} />
          <DownloadCsvButton reportType={ReportType.TrialBalance} params={{ asOfDate }} disabled={!rows} />
        </div>
      </div>

      {error && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-5 text-base text-destructive">{error}</div>
      )}

      {!error && rows === null && (
        <div className="flex flex-col gap-3">
          {Array.from({ length: 6 }).map((_, i) => (
            <Skeleton key={i} className="h-12 w-full" />
          ))}
        </div>
      )}

      {!error && rows !== null && rows.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <Scale className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No postable accounts as at this date.</p>
        </div>
      )}

      {!error && rows !== null && rows.length > 0 && (
        <div className="rounded-2xl bg-white p-6 shadow-sm ring-1 ring-black/5">
          <ReportHeader title="Trial Balance" subtitle={`As at ${formatReportDate(asOfDate)}`} />
          <Table className="mt-4 text-base">
            <TableHeader>
              <TableRow>
                <TableHead className="h-11 px-3 text-sm">Account</TableHead>
                <TableHead className="h-11 px-3 text-right text-sm">Debit</TableHead>
                <TableHead className="h-11 px-3 text-right text-sm">Credit</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {rows.map((row, i) => (
                <TableRow key={i}>
                  <TableCell className="px-3 py-2.5">
                    <span className="text-muted-foreground">{row.accountCode}</span>{" "}
                    <span>{row.accountName}</span>
                  </TableCell>
                  <TableCell className="px-3 py-2.5 text-right tabular-nums">{formatAmount(row.debit, true)}</TableCell>
                  <TableCell className="px-3 py-2.5 text-right tabular-nums">{formatAmount(row.credit, true)}</TableCell>
                </TableRow>
              ))}
            </TableBody>
            <TableFooter className="border-t-2 border-foreground/70 bg-transparent">
              <TableRow className="hover:bg-transparent">
                <TableCell className="px-3 py-3 font-bold">Total</TableCell>
                <TableCell className="px-3 py-3 text-right font-bold tabular-nums">{formatAmount(totalDebit)}</TableCell>
                <TableCell className="px-3 py-3 text-right font-bold tabular-nums">{formatAmount(totalCredit)}</TableCell>
              </TableRow>
            </TableFooter>
          </Table>
        </div>
      )}
    </div>
  )
}
