"use client"

import { useFormContext } from "react-hook-form"

import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import {
    useDocumentTotals,
    type DocumentLineItem,
} from "@/shared/hooks/use-document-totals"
import { DocumentTotalsSummary } from "@/shared/components/document-totals-summary"

import type { ExpenseFormValues } from "./expense.schema"

function parseTaxRateFromLabel(label: string | undefined | null): number | undefined {
    if (!label) return undefined
    const match = label.match(/\((\d+(?:\.\d+)?)%\)/)
    return match ? Number(match[1]) : undefined
}

export function ExpenseFormSummary() {
    const { watch } = useFormContext<ExpenseFormValues>()

    const items = watch("items") ?? []
    const discountType = watch("discount")
    const discountAmount = watch("discount_amount")
    const taxRelation = watch("tax")

    const taxRate = parseTaxRateFromLabel(taxRelation?.label)
    const taxLabel = taxRelation?.label ?? "Tax"

    const lineItems: DocumentLineItem[] = items.map((item) => ({
        quantity: item.quantity,
        rate: item.rate,
        discount_amount: item.discount_amount,
    }))

    const totals = useDocumentTotals({
        lineItems,
        discountType,
        discountAmount,
        taxRate,
    })

    if (!totals.hasLineItems) return null

    return (
        <Card>
            <CardHeader className="pb-3">
                <CardTitle className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
                    Summary
                </CardTitle>
            </CardHeader>
            <CardContent>
                <DocumentTotalsSummary
                    totals={totals}
                    discountType={discountType}
                    taxLabel={taxLabel}
                />
            </CardContent>
        </Card>
    )
}