"use client"

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

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

import { Badge } from "@/components/ui/badge"
import { buttonVariants } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"

type StatusFilter = ChequeBookStatus | "All"

const STATUS_BADGE: Record<ChequeBookStatus, string> = {
  [ChequeBookStatus.Active]: "bg-success/10 text-success",
  [ChequeBookStatus.Completed]: "bg-primary/10 text-primary",
  [ChequeBookStatus.Cancelled]: "bg-destructive/10 text-destructive",
}

export default function ChequeBooksPage() {
  const router = useRouter()
  const [books, setBooks] = useState<ChequeBook[] | null>(null)
  const [bankAccounts, setBankAccounts] = useState<CashAndBankAccountDto[] | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [status, setStatus] = useState<StatusFilter>("All")

  useEffect(() => {
    let cancelled = false
    Promise.all([
      chequeBooksApi.list(status === "All" ? undefined : { status }),
      bankAccounts ? Promise.resolve(bankAccounts) : bankAccountsApi.list(CashBankAccountType.Bank),
    ])
      .then(([result, banks]) => {
        if (cancelled) return
        setBooks(result.items)
        setBankAccounts(banks)
      })
      .catch((err) => {
        if (!cancelled) setError(errorMessage(err))
      })
    return () => {
      cancelled = true
    }
    // bankAccounts intentionally excluded — fetched once, reused across status re-fetches.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [status])

  const bankAccountsById = useMemo(() => new Map((bankAccounts ?? []).map((a) => [a.accountId, a])), [bankAccounts])

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Link href="/dashboard/accounts" className={cn(buttonVariants({ variant: "ghost", size: "icon-lg" }))}>
            <ArrowLeft className="size-5" />
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-foreground">Cheque Books</h1>
            <p className="text-base text-muted-foreground">Cheque books issued from this company&apos;s own supply.</p>
          </div>
        </div>
        <Link href="/dashboard/accounts/cheque-books/new" className={cn(buttonVariants({ size: "lg" }))}>
          <Plus className="size-5" />
          New Cheque Book
        </Link>
      </div>

      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
        <Select<StatusFilter> value={status} onValueChange={(v) => setStatus(v ?? "All")}>
          <SelectTrigger className="h-12! w-full text-base sm:w-48">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="All" label="All statuses" className="text-base">All statuses</SelectItem>
            <SelectItem value={ChequeBookStatus.Active} label="Active" className="text-base">Active</SelectItem>
            <SelectItem value={ChequeBookStatus.Completed} label="Completed" className="text-base">Completed</SelectItem>
            <SelectItem value={ChequeBookStatus.Cancelled} label="Cancelled" className="text-base">Cancelled</SelectItem>
          </SelectContent>
        </Select>
      </div>

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

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

      {!error && books !== null && books.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 cheque books yet.</p>
        </div>
      )}

      {!error && books !== null && books.length > 0 && (
        <Table className="text-base">
          <TableHeader>
            <TableRow>
              <TableHead className="h-12 px-3 text-sm">Cheque book no.</TableHead>
              <TableHead className="h-12 px-3 text-sm">Bank account</TableHead>
              <TableHead className="h-12 px-3 text-sm">Branch</TableHead>
              <TableHead className="h-12 px-3 text-sm">Range</TableHead>
              <TableHead className="h-12 px-3 text-sm">Leaves</TableHead>
              <TableHead className="h-12 px-3 text-sm">Received</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {books.map((b) => {
              const bank = bankAccountsById.get(b.bankAccountId)
              return (
                <TableRow
                  key={b.chequeBookNo}
                  className="cursor-pointer"
                  onClick={() => router.push(`/dashboard/accounts/cheque-books/${encodeURIComponent(b.chequeBookNo)}`)}
                >
                  <TableCell className="px-3 py-3.5 font-medium">{b.chequeBookNo}</TableCell>
                  <TableCell className="px-3 py-3.5 text-muted-foreground">
                    {bank ? bank.accountName : `#${b.bankAccountId}`}
                  </TableCell>
                  <TableCell className="px-3 py-3.5 text-muted-foreground">#{b.branchId}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    {b.startChequeNo} – {b.endChequeNo}
                  </TableCell>
                  <TableCell className="px-3 py-3.5">{b.totalLeaves}</TableCell>
                  <TableCell className="px-3 py-3.5 text-muted-foreground">{formatReportDate(b.receivedDate)}</TableCell>
                  <TableCell className="px-3 py-3.5">
                    <Badge variant="outline" className={cn("h-6 justify-center border-transparent text-sm", STATUS_BADGE[b.status])}>
                      {b.status}
                    </Badge>
                  </TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      )}
    </div>
  )
}
