"use client"

import { AlertTriangle, Plus, Save } 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, RhfSelectField } from "@/shared/components/form"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { useResourceForm } from "@/shared/hooks/use-resource-form"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"

import { DEPARTMENT_ROUTES } from "@garage/api"
import { DEPARTMENT_ASSIGNMENT_TYPE_OPTIONS } from "@/modules/services/department-assignment-types"
import { departmentFormSchema, type DepartmentFormValues } from "./department.schema"

export type DepartmentFormProps = {
    resourceId?: string | null
    initialData?: unknown
    onSuccess?: () => void
}

const DEFAULT_VALUES: DepartmentFormValues = {
    name: "",
    assignment_type: "none",
}

function mapToFormValues(data: unknown): DepartmentFormValues {
    const d = (data as any)?.data ?? data ?? {}
    return {
        name: d.name ?? "",
        assignment_type: d.assignment_type ?? "none",
    }
}

function mapFormToPayload(values: DepartmentFormValues) {
    return {
        name: values.name,
        assignment_type: values.assignment_type || undefined,
    }
}

export function DepartmentForm({ resourceId, initialData, onSuccess }: DepartmentFormProps) {
    const api = useAuthApi()

    const { form, isEditing } = useResourceForm<DepartmentFormValues, any>({
        schema: departmentFormSchema,
        defaultValues: DEFAULT_VALUES,
        resourceId,
        initialData,
        queryKey: [DEPARTMENT_ROUTES.BY_ID, resourceId],
        mapToFormValues,
    })

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: DepartmentFormValues) => {
            const payload = mapFormToPayload(values)
            const promise = isEditing && resourceId
                ? api.departments.update(resourceId, payload)
                : api.departments.create(payload)

            toast.promise(promise, {
                loading: isEditing ? "Updating department..." : "Creating department...",
                success: isEditing ? "Department updated successfully" : "Department created successfully",
                error: isEditing ? "Failed to update department" : "Failed to create department",
            })

            return promise
        },
        onSuccess: () => {
            form.reset()
            onSuccess?.()
        },
    })

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

            <FieldGroup>
                <RhfTextField
                    name="name"
                    label="Name"
                    placeholder="e.g. Mechanical"
                    required
                />
                <RhfSelectField
                    name="assignment_type"
                    label="Assignment Type"
                    placeholder="Select assignment type"
                    options={[...DEPARTMENT_ASSIGNMENT_TYPE_OPTIONS]}
                />

                <Button type="submit" variant="default" disabled={isPending}>
                    {isEditing ? <Save /> : <Plus />}
                    {isPending
                        ? (isEditing ? "Updating..." : "Creating...")
                        : (isEditing ? "Update Department" : "Create Department")}
                </Button>
            </FieldGroup>
        </Rhform>
    )
}