"use client"

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

import { bankAccountsApi, chequeBooksApi } from "@/lib/api/general-ledger"
import { errorMessage } from "@/lib/error-map"
import { formatAmount, formatReportDate } from "@/lib/format"
import { cn } from "@/lib/utils"
import { CashAndBankAccountDto, CashBankAccountType, ChequeBook, ChequePage, ChequePageIssueStatus } from "@/types/general-ledger"

import { Badge } from "@/components/ui/badge"
import { buttonVariants } from "@/components/ui/button"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { ChequePageDialog } from "@/components/accounts/ChequePageDialog"

const STATUS_BADGE: Record<ChequePageIssueStatus, string> = {
  [ChequePageIssueStatus.Unused]: "bg-muted text-muted-foreground",
  [ChequePageIssueStatus.Issued]: "bg-primary/10 text-primary",
  [ChequePageIssueStatus.Cleared]: "bg-success/10 text-success",
  [ChequePageIssueStatus.Bounced]: "bg-destructive/10 text-destructive",
  [ChequePageIssueStatus.Cancelled]: "bg-destructive/10 text-destructive",
  [ChequePageIssueStatus.Void]: "bg-muted text-muted-foreground",
}

export default function ChequeBookDetailPage() {
  const params = useParams<{ chequeBookNo: string }>()
  const chequeBookNo = decodeURIComponent(params.chequeBookNo)

  const [book, setBook] = useState<ChequeBook | null>(null)
  const [bankAccount, setBankAccount] = useState<CashAndBankAccountDto | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [selectedPage, setSelectedPage] = useState<ChequePage | null>(null)
  const [dialogOpen, setDialogOpen] = useState(false)

  useEffect(() => {
    let cancelled = false
    chequeBooksApi
      .get(chequeBookNo, true)
      .then((res) => {
        if (cancelled) return
        setBook(res)
        return bankAccountsApi.list(CashBankAccountType.Bank).then((banks) => {
          if (cancelled) return
          setBankAccount(banks.find((b) => b.accountId === res.bankAccountId) ?? null)
        })
      })
      .catch((err) => {
        if (!cancelled) setError(errorMessage(err))
      })
    return () => {
      cancelled = true
    }
  }, [chequeBookNo])

  function handlePageUpdated(updated: ChequePage) {
    setBook((prev) => (prev ? { ...prev, pages: prev.pages.map((p) => (p.chequeNo === updated.chequeNo ? updated : p)) } : prev))
    setSelectedPage(updated)
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <Link href="/dashboard/accounts/cheque-books" className={cn(buttonVariants({ variant: "ghost", size: "icon-lg" }))}>
          <ArrowLeft className="size-5" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-foreground">Cheque Book {chequeBookNo}</h1>
          <p className="text-base text-muted-foreground">Every leaf in this book — click one to view details or take an action.</p>
        </div>
      </div>

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

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

      {!error && book !== null && (
        <>
          <div className="grid grid-cols-2 gap-4 rounded-2xl bg-white p-6 shadow-sm ring-1 ring-black/5 sm:grid-cols-4">
            <div>
              <p className="text-sm text-muted-foreground">Bank account</p>
              <p className="text-base font-medium">{bankAccount ? bankAccount.accountName : `#${book.bankAccountId}`}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">Branch</p>
              <p className="text-base font-medium">#{book.branchId}</p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">Range</p>
              <p className="text-base font-medium">
                {book.startChequeNo} – {book.endChequeNo}
              </p>
            </div>
            <div>
              <p className="text-sm text-muted-foreground">Received</p>
              <p className="text-base font-medium">{formatReportDate(book.receivedDate)}</p>
            </div>
          </div>

          {book.pages.length === 0 ? (
            <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
              <BookText className="size-12 text-muted-foreground" />
              <p className="text-base text-muted-foreground">No pages found for this book.</p>
            </div>
          ) : (
            <Table className="text-base">
              <TableHeader>
                <TableRow>
                  <TableHead className="h-12 px-3 text-sm">Cheque no.</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Status</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Payee</TableHead>
                  <TableHead className="h-12 px-3 text-sm">Issue date</TableHead>
                  <TableHead className="h-12 px-3 text-sm text-right">Amount</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {book.pages.map((p) => (
                  <TableRow
                    key={p.chequeNo}
                    className="cursor-pointer"
                    onClick={() => {
                      setSelectedPage(p)
                      setDialogOpen(true)
                    }}
                  >
                    <TableCell className="px-3 py-3.5 font-medium">{p.chequeNo}</TableCell>
                    <TableCell className="px-3 py-3.5">
                      <Badge variant="outline" className={cn("h-6 justify-center border-transparent text-sm", STATUS_BADGE[p.issueStatus])}>
                        {p.issueStatus}
                      </Badge>
                    </TableCell>
                    <TableCell className="px-3 py-3.5">{p.payeeName ?? "—"}</TableCell>
                    <TableCell className="px-3 py-3.5 text-muted-foreground">{formatReportDate(p.issueDate)}</TableCell>
                    <TableCell className="px-3 py-3.5 text-right tabular-nums">
                      {p.amount !== null ? formatAmount(p.amount) : "—"}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </>
      )}

      <ChequePageDialog page={selectedPage} open={dialogOpen} onOpenChange={setDialogOpen} onUpdated={handlePageUpdated} />
    </div>
  )
}
