"use client"

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

import { receivedChequesApi } from "@/lib/api/general-ledger"
import { errorMessage } from "@/lib/error-map"
import { formatAmount, formatReportDate } from "@/lib/format"
import { cn } from "@/lib/utils"
import { ReceivedCheque, ReceivedChequeStatus } 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"
import { ReceivedChequeDialog } from "@/components/accounts/ReceivedChequeDialog"

type StatusFilter = ReceivedChequeStatus | "All"

const STATUS_BADGE: Record<ReceivedChequeStatus, string> = {
  [ReceivedChequeStatus.Received]: "bg-muted text-muted-foreground",
  [ReceivedChequeStatus.Deposited]: "bg-primary/10 text-primary",
  [ReceivedChequeStatus.Cleared]: "bg-success/10 text-success",
  [ReceivedChequeStatus.Returned]: "bg-destructive/10 text-destructive",
  [ReceivedChequeStatus.Cancelled]: "bg-destructive/10 text-destructive",
}

export default function ReceivedChequesPage() {
  const [cheques, setCheques] = useState<ReceivedCheque[] | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [status, setStatus] = useState<StatusFilter>("All")
  const [selected, setSelected] = useState<ReceivedCheque | null>(null)
  const [dialogOpen, setDialogOpen] = useState(false)

  useEffect(() => {
    let cancelled = false
    receivedChequesApi
      .list(status === "All" ? undefined : { status })
      .then((res) => {
        if (!cancelled) setCheques(res.items)
      })
      .catch((err) => {
        if (!cancelled) setError(errorMessage(err))
      })
    return () => {
      cancelled = true
    }
  }, [status])

  function handleUpdated(updated: ReceivedCheque) {
    setCheques((prev) => (prev ? prev.map((c) => (c.receivedChequeId === updated.receivedChequeId ? updated : c)) : prev))
    setSelected(updated)
  }

  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">Received Cheques</h1>
            <p className="text-base text-muted-foreground">Cheques received from customers, suppliers, or others.</p>
          </div>
        </div>
        <Link href="/dashboard/accounts/received-cheques/new" className={cn(buttonVariants({ size: "lg" }))}>
          <Plus className="size-5" />
          New Received Cheque
        </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={ReceivedChequeStatus.Received} label="Received" className="text-base">Received</SelectItem>
            <SelectItem value={ReceivedChequeStatus.Deposited} label="Deposited" className="text-base">Deposited</SelectItem>
            <SelectItem value={ReceivedChequeStatus.Cleared} label="Cleared" className="text-base">Cleared</SelectItem>
            <SelectItem value={ReceivedChequeStatus.Returned} label="Returned" className="text-base">Returned</SelectItem>
            <SelectItem value={ReceivedChequeStatus.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 && cheques === null && (
        <div className="flex flex-col gap-3">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full" />
          ))}
        </div>
      )}

      {!error && cheques !== null && cheques.length === 0 && (
        <div className="flex flex-col items-center gap-4 rounded-xl border border-dashed py-20 text-center">
          <Inbox className="size-12 text-muted-foreground" />
          <p className="text-base text-muted-foreground">No received cheques yet.</p>
        </div>
      )}

      {!error && cheques !== null && cheques.length > 0 && (
        <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">Received from</TableHead>
              <TableHead className="h-12 px-3 text-sm">Type</TableHead>
              <TableHead className="h-12 px-3 text-sm text-right">Amount</TableHead>
              <TableHead className="h-12 px-3 text-sm">Received</TableHead>
              <TableHead className="h-12 px-3 text-sm">Status</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {cheques.map((c) => (
              <TableRow
                key={c.receivedChequeId}
                className="cursor-pointer"
                onClick={() => {
                  setSelected(c)
                  setDialogOpen(true)
                }}
              >
                <TableCell className="px-3 py-3.5 font-medium">{c.chequeNo}</TableCell>
                <TableCell className="px-3 py-3.5">{c.receivedFromName}</TableCell>
                <TableCell className="px-3 py-3.5 text-muted-foreground">{c.receivedFromType}</TableCell>
                <TableCell className="px-3 py-3.5 text-right tabular-nums">{formatAmount(c.amount)}</TableCell>
                <TableCell className="px-3 py-3.5 text-muted-foreground">{formatReportDate(c.receivedDate)}</TableCell>
                <TableCell className="px-3 py-3.5">
                  <Badge variant="outline" className={cn("h-6 justify-center border-transparent text-sm", STATUS_BADGE[c.status])}>
                    {c.status}
                  </Badge>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}

      <ReceivedChequeDialog cheque={selected} open={dialogOpen} onOpenChange={setDialogOpen} onUpdated={handleUpdated} />
    </div>
  )
}
