"use client"

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

import { receivedChequesApi } from "@/lib/api/general-ledger"
import { errorMessage } from "@/lib/error-map"
import { validateReceivedChequeForm } from "@/lib/validations/general-ledger"
import { cn } from "@/lib/utils"
import { ReceivedFromType } 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 NewReceivedChequePage() {
  const router = useRouter()

  const [companyId, setCompanyId] = useState("")
  const [branchId, setBranchId] = useState("")
  const [receivedFromType, setReceivedFromType] = useState<ReceivedFromType>(ReceivedFromType.Customer)
  const [receivedFromId, setReceivedFromId] = useState("")
  const [receivedFromName, setReceivedFromName] = useState("")
  const [drawerBankName, setDrawerBankName] = useState("")
  const [drawerBankBranch, setDrawerBankBranch] = useState("")
  const [accountHolderName, setAccountHolderName] = useState("")
  const [chequeNo, setChequeNo] = useState("")
  const [chequeDate, setChequeDate] = useState("")
  const [amount, setAmount] = useState("")
  const [receivedDate, setReceivedDate] = useState("")
  const [referenceType, setReferenceType] = useState("")
  const [referenceId, setReferenceId] = useState("")
  const [notes, setNotes] = useState("")
  const [createdBy, setCreatedBy] = useState("")
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  async function handleSubmit() {
    const nextErrors = validateReceivedChequeForm({ companyId, receivedFromName, chequeNo, chequeDate, amount, receivedDate })
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    setSubmitting(true)
    try {
      const created = await receivedChequesApi.create({
        companyId: Number(companyId),
        branchId: branchId ? Number(branchId) : undefined,
        receivedFromType,
        receivedFromId: receivedFromId ? Number(receivedFromId) : undefined,
        receivedFromName,
        drawerBankName: drawerBankName || undefined,
        drawerBankBranch: drawerBankBranch || undefined,
        accountHolderName: accountHolderName || undefined,
        chequeNo,
        chequeDate,
        amount: Number(amount),
        receivedDate,
        referenceType: referenceType || undefined,
        referenceId: referenceId ? Number(referenceId) : undefined,
        notes: notes || undefined,
        createdBy: createdBy || undefined,
      })
      toast.success("Received cheque recorded", `${created.chequeNo} — ${created.receivedFromName}`)
      router.push("/dashboard/accounts/received-cheques")
    } catch (err) {
      toast.error("Could not record received cheque", errorMessage(err))
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <Link href="/dashboard/accounts/received-cheques" className={cn(buttonVariants({ variant: "ghost", size: "icon-lg" }))}>
          <ArrowLeft className="size-5" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-foreground">New Received Cheque</h1>
          <p className="text-base text-muted-foreground">Record a cheque received from a customer, supplier, or other party.</p>
        </div>
      </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.companyId}>
            <FieldLabel htmlFor="rc-company">Company ID</FieldLabel>
            <Input
              id="rc-company"
              type="number"
              value={companyId}
              onChange={(e) => setCompanyId(e.target.value)}
              placeholder="1"
              aria-invalid={!!errors.companyId}
            />
            <FieldError errors={[errors.companyId ? { message: errors.companyId } : undefined]} />
          </Field>
          <Field>
            <FieldLabel htmlFor="rc-branch">Branch ID (optional)</FieldLabel>
            <Input id="rc-branch" type="number" value={branchId} onChange={(e) => setBranchId(e.target.value)} />
          </Field>

          <Field>
            <FieldLabel htmlFor="rc-from-type">Received from type</FieldLabel>
            <Select<ReceivedFromType> value={receivedFromType} onValueChange={(v) => setReceivedFromType(v ?? ReceivedFromType.Customer)}>
              <SelectTrigger id="rc-from-type" className="w-full text-base">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {Object.values(ReceivedFromType).map((t) => (
                  <SelectItem key={t} value={t} label={t} className="text-base">
                    {t}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </Field>

          <Field data-invalid={!!errors.receivedFromName}>
            <FieldLabel htmlFor="rc-from-name">Received from name</FieldLabel>
            <Input
              id="rc-from-name"
              value={receivedFromName}
              onChange={(e) => setReceivedFromName(e.target.value)}
              aria-invalid={!!errors.receivedFromName}
            />
            <FieldError errors={[errors.receivedFromName ? { message: errors.receivedFromName } : undefined]} />
          </Field>
          <Field>
            <FieldLabel htmlFor="rc-from-id">Received from ID (optional)</FieldLabel>
            <Input id="rc-from-id" type="number" value={receivedFromId} onChange={(e) => setReceivedFromId(e.target.value)} />
          </Field>

          <Field>
            <FieldLabel htmlFor="rc-drawer-bank">Drawer bank (optional)</FieldLabel>
            <Input id="rc-drawer-bank" value={drawerBankName} onChange={(e) => setDrawerBankName(e.target.value)} />
          </Field>
          <Field>
            <FieldLabel htmlFor="rc-drawer-branch">Drawer branch (optional)</FieldLabel>
            <Input id="rc-drawer-branch" value={drawerBankBranch} onChange={(e) => setDrawerBankBranch(e.target.value)} />
          </Field>
          <Field>
            <FieldLabel htmlFor="rc-holder">Account holder name (optional)</FieldLabel>
            <Input id="rc-holder" value={accountHolderName} onChange={(e) => setAccountHolderName(e.target.value)} />
          </Field>

          <Field data-invalid={!!errors.chequeNo}>
            <FieldLabel htmlFor="rc-cheque-no">Cheque number</FieldLabel>
            <Input id="rc-cheque-no" value={chequeNo} onChange={(e) => setChequeNo(e.target.value)} aria-invalid={!!errors.chequeNo} />
            <FieldError errors={[errors.chequeNo ? { message: errors.chequeNo } : undefined]} />
          </Field>
          <Field data-invalid={!!errors.chequeDate}>
            <FieldLabel htmlFor="rc-cheque-date">Cheque date</FieldLabel>
            <Input
              id="rc-cheque-date"
              type="date"
              value={chequeDate}
              onChange={(e) => setChequeDate(e.target.value)}
              aria-invalid={!!errors.chequeDate}
            />
            <FieldError errors={[errors.chequeDate ? { message: errors.chequeDate } : undefined]} />
          </Field>

          <Field data-invalid={!!errors.amount}>
            <FieldLabel htmlFor="rc-amount">Amount</FieldLabel>
            <Input id="rc-amount" type="number" value={amount} onChange={(e) => setAmount(e.target.value)} aria-invalid={!!errors.amount} />
            <FieldError errors={[errors.amount ? { message: errors.amount } : undefined]} />
          </Field>
          <Field data-invalid={!!errors.receivedDate}>
            <FieldLabel htmlFor="rc-received-date">Received date</FieldLabel>
            <Input
              id="rc-received-date"
              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="rc-ref-type">Reference type (optional)</FieldLabel>
            <Input id="rc-ref-type" value={referenceType} onChange={(e) => setReferenceType(e.target.value)} placeholder="Invoice" />
          </Field>
          <Field>
            <FieldLabel htmlFor="rc-ref-id">Reference ID (optional)</FieldLabel>
            <Input id="rc-ref-id" type="number" value={referenceId} onChange={(e) => setReferenceId(e.target.value)} />
          </Field>

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

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