"use client"

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

import { bankAccountsApi, chequeBooksApi } from "@/lib/api/general-ledger"
import { errorMessage } from "@/lib/error-map"
import { validateChequeBookForm } from "@/lib/validations/general-ledger"
import { cn } from "@/lib/utils"
import { CashAndBankAccountDto, CashBankAccountType } from "@/types/general-ledger"

import { Button, buttonVariants } from "@/components/ui/button"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { toast } from "@/components/ui/toast"

export default function NewChequeBookPage() {
  const router = useRouter()

  const [bankAccounts, setBankAccounts] = useState<CashAndBankAccountDto[] | null>(null)
  const [bankAccountsError, setBankAccountsError] = useState<string | null>(null)

  const [branchId, setBranchId] = useState("")
  const [bankAccountId, setBankAccountId] = useState("")
  const [chequeBookNo, setChequeBookNo] = useState("")
  const [startChequeNo, setStartChequeNo] = useState("")
  const [endChequeNo, setEndChequeNo] = useState("")
  const [totalLeaves, setTotalLeaves] = useState("")
  const [receivedDate, setReceivedDate] = useState("")
  const [description, setDescription] = useState("")
  const [createdBy, setCreatedBy] = useState("")
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  // Cheque books can only be tied to a real bank account — GL's own module note (§5.8) says
  // statement import/reconcile, and by extension cheque books, are bank_account-only, never cash_account.
  useEffect(() => {
    bankAccountsApi
      .list(CashBankAccountType.Bank)
      .then(setBankAccounts)
      .catch((err) => setBankAccountsError(errorMessage(err)))
  }, [])

  async function handleSubmit() {
    const nextErrors = validateChequeBookForm({
      branchId,
      bankAccountId,
      chequeBookNo,
      startChequeNo,
      endChequeNo,
      totalLeaves,
      receivedDate,
    })
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    setSubmitting(true)
    try {
      const created = await chequeBooksApi.create({
        branchId: Number(branchId),
        bankAccountId: Number(bankAccountId),
        chequeBookNo,
        startChequeNo,
        endChequeNo,
        totalLeaves: Number(totalLeaves),
        receivedDate,
        description: description || undefined,
        createdBy: createdBy || undefined,
      })
      toast.success("Cheque book created", `${created.chequeBookNo} — ${created.totalLeaves} leaves`)
      router.push(`/dashboard/accounts/cheque-books/${encodeURIComponent(created.chequeBookNo)}`)
    } catch (err) {
      toast.error("Could not create cheque book", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  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">New Cheque Book</h1>
          <p className="text-base text-muted-foreground">
            Every leaf from the start to end cheque number is generated automatically, all &quot;Unused&quot;.
          </p>
        </div>
      </div>

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

      <div className="rounded-2xl bg-white p-6 shadow-sm ring-1 ring-black/5">
        <div className="grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2 lg:grid-cols-3">
          <Field data-invalid={!!errors.bankAccountId}>
            <FieldLabel htmlFor="cb-bank">Bank account</FieldLabel>
            <Select<string> value={bankAccountId} onValueChange={(v) => setBankAccountId(v ?? "")}>
              <SelectTrigger id="cb-bank" className="w-full text-base" aria-invalid={!!errors.bankAccountId}>
                <SelectValue placeholder={bankAccounts === null ? "Loading…" : "Select a bank account"} />
              </SelectTrigger>
              <SelectContent>
                {(bankAccounts ?? []).map((a) => (
                  <SelectItem key={a.accountId} value={String(a.accountId)} label={a.accountName} className="text-base">
                    {a.accountName}
                    {a.bankName ? ` — ${a.bankName}` : ""}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <FieldError errors={[errors.bankAccountId ? { message: errors.bankAccountId } : undefined]} />
          </Field>

          <Field data-invalid={!!errors.branchId}>
            <FieldLabel htmlFor="cb-branch">Branch ID</FieldLabel>
            <Input
              id="cb-branch"
              type="number"
              value={branchId}
              onChange={(e) => setBranchId(e.target.value)}
              placeholder="1"
              aria-invalid={!!errors.branchId}
            />
            <FieldError errors={[errors.branchId ? { message: errors.branchId } : undefined]} />
          </Field>

          <Field data-invalid={!!errors.chequeBookNo}>
            <FieldLabel htmlFor="cb-no">Cheque book number</FieldLabel>
            <Input
              id="cb-no"
              value={chequeBookNo}
              onChange={(e) => setChequeBookNo(e.target.value)}
              placeholder="CB-0001"
              aria-invalid={!!errors.chequeBookNo}
            />
            <FieldError errors={[errors.chequeBookNo ? { message: errors.chequeBookNo } : undefined]} />
          </Field>

          <Field data-invalid={!!errors.startChequeNo}>
            <FieldLabel htmlFor="cb-start">Start cheque no.</FieldLabel>
            <Input
              id="cb-start"
              value={startChequeNo}
              onChange={(e) => setStartChequeNo(e.target.value)}
              placeholder="000001"
              aria-invalid={!!errors.startChequeNo}
            />
            <FieldError errors={[errors.startChequeNo ? { message: errors.startChequeNo } : undefined]} />
          </Field>
          <Field data-invalid={!!errors.endChequeNo}>
            <FieldLabel htmlFor="cb-end">End cheque no.</FieldLabel>
            <Input
              id="cb-end"
              value={endChequeNo}
              onChange={(e) => setEndChequeNo(e.target.value)}
              placeholder="000025"
              aria-invalid={!!errors.endChequeNo}
            />
            <FieldError errors={[errors.endChequeNo ? { message: errors.endChequeNo } : undefined]} />
          </Field>

          <Field data-invalid={!!errors.totalLeaves}>
            <FieldLabel htmlFor="cb-leaves">Total leaves</FieldLabel>
            <Input
              id="cb-leaves"
              type="number"
              value={totalLeaves}
              onChange={(e) => setTotalLeaves(e.target.value)}
              placeholder="25"
              aria-invalid={!!errors.totalLeaves}
            />
            <p className="text-sm text-muted-foreground">Must equal end − start + 1.</p>
            <FieldError errors={[errors.totalLeaves ? { message: errors.totalLeaves } : undefined]} />
          </Field>

          <Field data-invalid={!!errors.receivedDate}>
            <FieldLabel htmlFor="cb-received">Received date</FieldLabel>
            <Input
              id="cb-received"
              type="date"
              value={receivedDate}
              onChange={(e) => setReceivedDate(e.target.value)}
              aria-invalid={!!errors.receivedDate}
            />
            <FieldError errors={[errors.receivedDate ? { message: errors.receivedDate } : undefined]} />
          </Field>

          <Field>
            <FieldLabel htmlFor="cb-desc">Description (optional)</FieldLabel>
            <Input id="cb-desc" value={description} onChange={(e) => setDescription(e.target.value)} />
          </Field>

          <Field>
            <FieldLabel htmlFor="cb-by">Created by (optional)</FieldLabel>
            <Input id="cb-by" value={createdBy} onChange={(e) => setCreatedBy(e.target.value)} />
          </Field>
        </div>

        <div className="mt-6 flex justify-end gap-3">
          <Link href="/dashboard/accounts/cheque-books" className={cn(buttonVariants({ variant: "outline" }), "min-w-36")}>
            Cancel
          </Link>
          <Button className="min-w-36" onClick={handleSubmit} disabled={submitting}>
            {submitting ? "Creating…" : "Create"}
          </Button>
        </div>
      </div>
    </div>
  )
}
