"use client"

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

import { reportsApi } from "@/lib/api/general-ledger"
import { errorMessage } from "@/lib/error-map"
import { formatReportDate, startOfMonthIso, todayIso } from "@/lib/format"
import { cn } from "@/lib/utils"
import { ProfitAndLossResponse, ProfitAndLossSection, ReportType } 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 { DownloadCsvButton } from "@/components/reports/DownloadCsvButton"
import { DownloadPdfButton } from "@/components/reports/DownloadPdfButton"
import { ReportHeader } from "@/components/reports/ReportHeader"
import { ReportSection } from "@/components/reports/ReportSection"
import { ReportSubtotal } from "@/components/reports/ReportSubtotal"

function pnlSectionLines(section: ProfitAndLossSection | undefined) {
  return (section?.lines ?? []).map((line) => ({
    label: (
      <>
        <span className="text-muted-foreground">{line.accountCode}</span> <span>{line.accountName}</span>
      </>
    ),
    amount: line.amount,
  }))
}

export default function ProfitAndLossPage() {
  const [periodStart, setPeriodStart] = useState(startOfMonthIso())
  const [periodEnd, setPeriodEnd] = useState(todayIso())
  const [report, setReport] = useState<ProfitAndLossResponse | null>(null)
  const [error, setError] = useState<string | null>(null)

  // Clears stale results the instant the period 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 periodKey = `${periodStart}|${periodEnd}`
  const [loadedFor, setLoadedFor] = useState<string | null>(null)
  if (loadedFor !== periodKey) {
    setLoadedFor(periodKey)
    setReport(null)
    setError(null)
  }

  useEffect(() => {
    if (!periodStart || !periodEnd) return
    let cancelled = false
    reportsApi
      .profitAndLoss(periodStart, periodEnd)
      .then((res) => {
        if (!cancelled) setReport(res)
      })
      .catch((err) => {
        if (!cancelled) setError(errorMessage(err))
      })
    return () => {
      cancelled = true
    }
  }, [periodStart, periodEnd])

  // GL omits an empty/zero section entirely rather than sending `{ lines: [], total: 0 }` —
  // confirmed on Cash Flow's equivalent fields, same inferred nested-section shape here.
  const isEmpty =
    report !== null &&
    (report.sales?.lines?.length ?? 0) === 0 &&
    (report.costOfSales?.lines?.length ?? 0) === 0 &&
    (report.otherIncome?.lines?.length ?? 0) === 0 &&
    (report.distributionExpenses?.lines?.length ?? 0) === 0 &&
    (report.administrationExpenses?.lines?.length ?? 0) === 0 &&
    (report.otherExpenses?.lines?.length ?? 0) === 0 &&
    (report.financialExpenses?.lines?.length ?? 0) === 0 &&
    (report.unclassified?.lines?.length ?? 0) === 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">Profit &amp; Loss</h1>
          <p className="text-base text-muted-foreground">Statement of Profit or Loss — Income and Expense for a period.</p>
        </div>
      </div>

      <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
        <div className="grid grid-cols-2 gap-3 sm:flex sm:items-end">
          <div className="flex flex-col gap-1.5">
            <Label className="text-base">From</Label>
            <Input type="date" value={periodStart} onChange={(e) => setPeriodStart(e.target.value)} className="h-11 text-base" />
          </div>
          <div className="flex flex-col gap-1.5">
            <Label className="text-base">To</Label>
            <Input type="date" value={periodEnd} onChange={(e) => setPeriodEnd(e.target.value)} className="h-11 text-base" />
          </div>
        </div>
        <div className="flex gap-2">
          <DownloadPdfButton reportType={ReportType.ProfitAndLoss} params={{ periodStart, periodEnd }} disabled={!report} />
          <DownloadCsvButton reportType={ReportType.ProfitAndLoss} params={{ periodStart, periodEnd }} disabled={!report} />
        </div>
      </div>

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

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

      {!error && isEmpty && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <LineChart className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No Income/Expense accounts posted in this period.</p>
        </div>
      )}

      {!error && report !== null && !isEmpty && (
        <div className="rounded-2xl bg-white p-6 shadow-sm ring-1 ring-black/5">
          <ReportHeader
            title="Statement of Profit or Loss"
            subtitle={`For the period ${formatReportDate(periodStart)} to ${formatReportDate(periodEnd)}`}
          />

          <div className="mt-4">
            <ReportSection title="Sales" lines={pnlSectionLines(report.sales)} total={report.sales?.total} />
            <ReportSection title="Cost of Sales" lines={pnlSectionLines(report.costOfSales)} total={report.costOfSales?.total} />
            <ReportSubtotal label="Gross Profit" amount={report.grossProfit} />
            <ReportSection title="Other Income" lines={pnlSectionLines(report.otherIncome)} total={report.otherIncome?.total} />
            <ReportSection
              title="Distribution Expenses"
              lines={pnlSectionLines(report.distributionExpenses)}
              total={report.distributionExpenses?.total}
            />
            <ReportSection
              title="Administration Expenses"
              lines={pnlSectionLines(report.administrationExpenses)}
              total={report.administrationExpenses?.total}
            />
            <ReportSection title="Other Expenses" lines={pnlSectionLines(report.otherExpenses)} total={report.otherExpenses?.total} />
            <ReportSection
              title="Financial Expenses"
              lines={pnlSectionLines(report.financialExpenses)}
              total={report.financialExpenses?.total}
            />
            {report.unclassified && (
              <ReportSection title="Unclassified" lines={pnlSectionLines(report.unclassified)} total={report.unclassified?.total} />
            )}
            <ReportSubtotal label="Net Profit for the Period" amount={report.netProfitForPeriod} large />
          </div>
        </div>
      )}
    </div>
  )
}
