"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,
    RhfTextareaField,
    RhfSelectField,
    RhfAsyncSelectField,
    RhfTimeField,
} 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 { toRelation, toId } from "@/shared/lib/utils"

import {
    appointmentFormSchema,
    type AppointmentFormValues,
    APPOINTMENT_STATUS_OPTIONS,
} from "./appointment.schema"
import { RhfVehicleSelectField } from "@/modules/vehicles/rhf-vehicle-select-field"
import { RhfCustomerSelectField } from "@/modules/customers/rhf-customer-select-field"
import { RhfEmployeeSelectField } from "@/modules/employees/rhf-employee-select-field"

// ── Props ──

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

// ── Default values ──

const DEFAULT_VALUES: AppointmentFormValues = {
    title: "",
    date: "",
    from_time: "00:00:00",
    to_time: "00:00:00",
    customer: null,
    vehicle: null,
    service_writer: null,
    technician: null,
    department: null,
    job_card: null,
    notes: "",
    status: "requested",
}

// ── Mapping helpers ──

function mapToFormValues(data: unknown): AppointmentFormValues {
    const d = (data as any)?.data ?? data ?? {}

    return {
        title: d.title || "",
        date: d.date || "",
        from_time: d.from_time || "",
        to_time: d.to_time || "",
        customer: toRelation(d.customer_id, d.customer_name),
        vehicle: toRelation(d.vehicle_id, d.vehicle_name),
        service_writer: toRelation(d.service_writer_id, d.service_writer_name),
        technician: toRelation(d.technician_id, d.technician_name),
        department: toRelation(d.department_id, d.department_name),
        job_card: toRelation(d.job_card_id, d.job_card_title),
        notes: d.notes || "",
        status: d.status || "requested",
    }
}

function mapFormToPayload(values: AppointmentFormValues) {
    return {
        title: values.title,
        date: values.date,
        from_time: values.from_time,
        to_time: values.to_time,
        customer_id: toId(values.customer),
        vehicle_id: toId(values.vehicle),
        service_writer_id: toId(values.service_writer),
        technician_id: toId(values.technician),
        department_id: toId(values.department),
        job_card_id: toId(values.job_card),
        notes: values.notes || undefined,
        status: values.status || undefined,
    }
}

// ── Shared helpers ──

const mapLookupOption = (item: any) => ({
    value: String(item.id),
    label: item.name ?? item.title ?? String(item.id),
})

const mapJobCardOption = (item: any) => ({
    value: String(item.id),
    label: item.title || `Job Card #${item.id}`,
})

const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }

// ── Component ──

export function AppointmentForm({ resourceId, initialData, onSuccess }: AppointmentFormProps) {
    const api = useAuthApi()

    const { form, isEditing } = useResourceForm<AppointmentFormValues>({
        schema: appointmentFormSchema,
        defaultValues: DEFAULT_VALUES,
        resourceId,
        initialData,
        mapToFormValues,
    })

    const { mutate, isPending, error } = useFormMutation(form, {
        mutationFn: (values: AppointmentFormValues) => {
            const payload = mapFormToPayload(values)
            const promise = (isEditing && resourceId
                ? api.appointments.update(resourceId, payload as any)
                : api.appointments.create(payload as any)) as Promise<any>
            toast.promise(promise, {
                loading: isEditing ? "Updating appointment..." : "Creating appointment...",
                success: isEditing ? "Appointment updated." : "Appointment created.",
                error: isEditing ? "Failed to update appointment." : "Failed to create appointment.",
            })
            return promise
        },
        onSuccess: () => {
            form.reset()
            onSuccess?.()
        },
    })

    return (
        <Rhform form={form} onSubmit={(values) => mutate(values)} className="space-y-6">
            {error && (
                <Alert variant="destructive">
                    <AlertTriangle className="size-4" />
                    <AlertTitle>{error.message}</AlertTitle>
                </Alert>
            )}

            <FieldGroup>
                <RhfTextField name="title" label="Title" placeholder="e.g. Oil Change Appointment" required />
                <div className="grid grid-cols-2 gap-4">
                    <RhfTextField name="date" label="Date" placeholder="YYYY-MM-DD" type="date" />
                    <RhfSelectField
                        name="status"
                        label="Status"
                        options={APPOINTMENT_STATUS_OPTIONS}
                        placeholder="Select status"
                    />
                </div>
                <div className="grid grid-cols-2 gap-4">
                    <RhfTimeField name="from_time" label="From Time" placeholder="HH:MM"   />
                    <RhfTimeField name="to_time" label="To Time" placeholder="HH:MM"   />
                </div>
            </FieldGroup>

            <FieldGroup>
                <RhfCustomerSelectField name="customer" />
                <RhfVehicleSelectField name="vehicle" />
            </FieldGroup>

            <FieldGroup>
                <RhfEmployeeSelectField name="service_writer" label="Service Writer" />
                <RhfEmployeeSelectField name="technician" label="Technician" />
                <RhfAsyncSelectField
                    name="department"
                    label="Department"
                    placeholder="Select department..."
                    queryKey={["departments-lookup"]}
                    listFn={() => api.departments.list()}
                    mapOption={mapLookupOption}
                    {...STORE_OBJECT}
                />
            </FieldGroup>

            <FieldGroup>
                <RhfAsyncSelectField
                    name="job_card"
                    label="Job Card (optional)"
                    placeholder="Select job card..."
                    queryKey={["job-cards-lookup"]}
                    listFn={() => api.jobCards.list()}
                    mapOption={mapJobCardOption}
                    {...STORE_OBJECT}
                />
            </FieldGroup>

            <FieldGroup>
                <RhfTextareaField name="notes" label="Notes" placeholder="Additional notes..." />
            </FieldGroup>

            <Button type="submit" disabled={isPending} className="w-full">
                {isEditing ? <Save className="size-4" /> : <Plus className="size-4" />}
                {isPending
                    ? (isEditing ? "Saving..." : "Creating...")
                    : (isEditing ? "Save Changes" : "Create Appointment")}
            </Button>
        </Rhform>
    )
}
