"use client"

import { AlertTriangle, Plus } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
import { FieldGroup } from "@/shared/components/ui/field"
import {
    Rhform,
    RhfTextField,
    RhfTextareaField,
} from "@/shared/components/form"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"

const schema = z.object({
    period_start: z.string().min(1, "Required"),
    period_end: z.string().min(1, "Required"),
    reference: z.string().max(50).optional(),
    note: z.string().max(2000).optional(),
})

type PayrollRunFormValues = z.infer<typeof schema>

function firstOfMonth() {
    const d = new Date()
    return new Date(d.getFullYear(), d.getMonth(), 1).toISOString().slice(0, 10)
}
function lastOfMonth() {
    const d = new Date()
    return new Date(d.getFullYear(), d.getMonth() + 1, 0).toISOString().slice(0, 10)
}

export type PayrollRunFormProps = {
    onSuccess?: (runId?: string) => void
}

export function PayrollRunForm({ onSuccess }: PayrollRunFormProps) {
    const api = useAuthApi()

    const form = useForm<PayrollRunFormValues>({
        resolver: zodResolver(schema),
        defaultValues: {
            period_start: firstOfMonth(),
            period_end: lastOfMonth(),
            reference: "",
            note: "",
        },
    })

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: PayrollRunFormValues) => {
            const payload = {
                period_start: values.period_start,
                period_end: values.period_end,
                reference: values.reference || undefined,
                note: values.note || undefined,
            }
            const promise = api.payroll.create(payload)
            toast.promise(promise, {
                loading: "Creating run + generating entries...",
                success: "Payroll run created",
                error: "Failed to create run",
            })
            return promise
        },
        onSuccess: (res: any) => {
            const runId = res?.data?.id ?? res?.id
            form.reset()
            onSuccess?.(runId ? String(runId) : undefined)
        },
    })

    return (
        <Rhform form={form} onSubmit={(values) => mutate(values)}>
            {error && (
                <Alert variant="destructive" className="mb-4">
                    <AlertTriangle className="me-2 h-4 w-4" />
                    <AlertTitle>Failed to create payroll run</AlertTitle>
                    {error.message}
                </Alert>
            )}

            <FieldGroup>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField name="period_start" label="Period Start" type="date" required />
                    <RhfTextField name="period_end" label="Period End" type="date" required />
                </div>

                <RhfTextField name="reference" label="Reference" placeholder="Auto if blank" />

                <RhfTextareaField name="note" label="Note" rows={2} />

                <Button type="submit" variant="default" disabled={isPending}>
                    <Plus />
                    {isPending ? "Creating..." : "Create & Generate"}
                </Button>
            </FieldGroup>
        </Rhform>
    )
}
