"use client"

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

import { Button } from "@/shared/components/ui/button"
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/shared/components/ui/dialog"
import {
    Rhform,
    RhfTextField,
    RhfTextareaField,
    RhfCheckboxField,
    RhfSelectField,
    RhfAsyncSelectField,
    RhfDateField,
    RhfTimeField,
    RhfAutoGenerateField,
} 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 { formatTaxLabel } from "@/shared/utils/formatters"

import {
    jobCardFormSchema,
    type JobCardFormValues,
    FUEL_LEVEL_OPTIONS,
    JOB_CARD_STATUS_OPTIONS,
    DISCOUNT_TYPE_OPTIONS,
} from "./job-card.schema"
import { JOB_CARD_ROUTES, EMPLOYEE_ROUTES, DEPARTMENT_ROUTES, INSURANCE_TYPE_ROUTES, TAX_ROUTES } from "@garage/api"
import { RhfCustomerSelectField } from "@/modules/customers/rhf-customer-select-field"
import { RhfVehicleSelectField } from "@/modules/vehicles/rhf-vehicle-select-field"
import { RhfLabelPickerField } from "@/modules/labels/rhf-label-picker-field"
import { RhfCustomerRemarksField } from "@/modules/estimates/rhf-customer-remarks-field"
import { InsuranceTypeCrudDialog } from "./insurance-type-crud-dialog"
import { RhfEmployeeSelectField } from "../employees/rhf-employee-select-field"

// ── Props ──

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

// ── Default values ──

const DEFAULT_VALUES: JobCardFormValues = {
    title: "",
    customer: null,
    vehicle: null,
    estimate: null,
    department: null,
    service_writer: null,
    primary_technician: null,
    sales_person: null,
    insurance_type: null,
    insurer: null,
    tax: null,
    order_number: "",
    estimate_number: "",
    status: "check_in",
    estimate_to: "Customer",
    tax_inclusive: "Tax Inclusive",
    discount_type: "no",
    discount_amount: undefined,
    discount_at: "inclusive_of_tax",
    order_date: new Date().toISOString().split("T")[0],
    check_in_date: "",
    check_in_time: "",
    start_date: "",
    // Must be initialized with 00:00:00
    start_time: "00:00:00",
    delivery_date: "",
    delivery_time: "00:00:00",
    km_in: "",
    fuel_level: "",
    has_insurance: false,
    enable_parts_issuing: false,
    enable_digital_authorisation: false,
    footer: "",
    attachments: "",
    customer_remarks: [],
    documents: [],
    attachment_files: [],
    label_ids: [],
    labels: [],
}

// ── Mapping helpers ──

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

    const mapTime = (v: unknown): string => {
        if (!v || typeof v !== "string") return ""
        if (v.includes("T")) return v.split("T")[1]?.slice(0, 8) ?? ""
        return v
    }
    const mapDate = (v: unknown): string => {
        if (!v || typeof v !== "string") return ""
        return v.split("T")[0]
    }

    return {
        title: d.title || "",
        customer: toRelation(d.customer_id, d.customer ? `${d.customer.first_name} ${d.customer.last_name}` : undefined),
        vehicle: toRelation(d.vehicle_id, d.vehicle ? (d.vehicle.plate_number ?? `${d.vehicle.make ?? ""} ${d.vehicle.model ?? ""}`.trim()) : undefined),
        estimate: toRelation(d.estimate_id, d.estimate?.estimate_number),
        department: toRelation(d.department_id, d.department?.name ?? d.department_name ?? d.department_title),
        service_writer: toRelation(d.service_writer_id, d.service_writer ? `${d.service_writer.first_name} ${d.service_writer.last_name}` : undefined),
        primary_technician: toRelation(d.primary_technician_id, d.primary_technician ? `${d.primary_technician.first_name} ${d.primary_technician.last_name}` : undefined),
        sales_person: toRelation(d.sales_person_id, d.sales_person ? `${d.sales_person.first_name} ${d.sales_person.last_name}` : undefined),
        insurance_type: toRelation(d.insurance_type_id, d.insurance_type?.name),
        insurer: toRelation(d.insurer_id, d.insurer ? `${d.insurer.first_name} ${d.insurer.last_name}`.trim() || d.insurer.company_name : undefined),
        tax: toRelation(d.tax_id, formatTaxLabel(d.tax, "") || undefined),
        order_number: d.order_number || "",
        estimate_number: d.estimate_number || "",
        status: d.status || "draft",
        estimate_to: d.estimate_to || "Customer",
        tax_inclusive: d.tax_inclusive || "Tax Inclusive",
        discount_type: d.discount_type || "no",
        discount_amount: d.discount_amount != null ? Number(d.discount_amount) : undefined,
        discount_at: d.discount_at || "inclusive_of_tax",
        order_date: mapDate(d.order_date),
        check_in_date: mapDate(d.check_in_date),
        check_in_time: mapTime(d.check_in_time),
        start_date: mapDate(d.start_date),
        start_time: mapTime(d.start_time),
        delivery_date: mapDate(d.delivery_date),
        delivery_time: mapTime(d.delivery_time),
        km_in: d.km_in != null ? String(d.km_in) : "",
        fuel_level: d.fuel_level || "",
        has_insurance: d.has_insurance ?? false,
        enable_parts_issuing: d.enable_parts_issuing ?? false,
        enable_digital_authorisation: d.enable_digital_authorisation ?? false,
        footer: d.footer || "",
        attachments: d.attachments || "",
        customer_remarks: Array.isArray(d.customer_remarks)
            ? d.customer_remarks.map((r: any) =>
                typeof r === "string" ? r : (r?.remark ?? "")
            ).filter(Boolean)
            : [],
        documents: Array.isArray(d.documents) ? d.documents : [],
        attachment_files: Array.isArray(d.attachment_files) ? d.attachment_files : [],
        label_ids: Array.isArray(d.label_ids)
            ? d.label_ids
                .map((id: any) => Number(id))
                .filter((id: number) => Number.isFinite(id))
            : [],
        labels: (d.labels ?? []).map((l: any) => ({
            id: l.id,
            title: l.title,
            color_code: l.color_code,
        })),
    }
}

function mapFormToPayload(values: JobCardFormValues) {
    return {
        title: values.title,
        customer_id: toId(values.customer),
        vehicle_id: toId(values.vehicle),
        estimate_id: toId(values.estimate) ?? undefined,
        department_id: toId(values.department),
        service_writer_id: toId(values.service_writer),
        primary_technician_id: toId(values.primary_technician),
        sales_person_id: toId(values.sales_person),
        insurance_type_id: values.insurance_type ? String(toId(values.insurance_type)) : null,
        insurer_id: values.insurer ? String(toId(values.insurer)) : null,
        tax_id: toId(values.tax) ?? undefined,
        estimate_number: values.estimate_number || undefined,
        order_number: values.order_number || undefined,
        status: values.status || undefined,
        estimate_to: values.estimate_to || undefined,
        tax_inclusive: values.tax_inclusive || undefined,
        discount_type: values.discount_type || undefined,
        discount_amount: values.discount_amount,
        discount_at: values.discount_at || undefined,
        order_date: values.order_date || undefined,
        check_in_date: values.check_in_date || undefined,
        check_in_time: values.check_in_time || undefined,
        start_date: values.start_date || undefined,
        start_time: values.start_time || undefined,
        delivery_date: values.delivery_date || undefined,
        delivery_time: values.delivery_time || undefined,
        km_in: values.km_in ? Number(values.km_in) : undefined,
        fuel_level: values.fuel_level || undefined,
        has_insurance: values.has_insurance,
        enable_parts_issuing: values.enable_parts_issuing,
        enable_digital_authorisation: values.enable_digital_authorisation,
        footer: values.footer || undefined,
        attachments: values.attachments || undefined,
        customer_remarks: values.customer_remarks?.filter(Boolean) ?? [],
        documents: values.documents,
        attachment_files: values.attachment_files,
        label_ids: values.labels?.map((l) => l.id) ?? values.label_ids,
    }
}

// ── Shared mapOption for async selects ──

const mapLookupOption = (item: any, labelKey: string = "name") => ({
    value: String(item.id),
    label: item[labelKey],
})



const mapEmployeeOption = (item: any) => ({
    value: String(item.id),
    label: `${item.first_name} ${item.last_name}`,
})

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

// ── Component ──

export function JobCardForm({ resourceId, initialData, onSuccess }: JobCardFormProps) {
    const api = useAuthApi()
    const [isCheckInDialogOpen, setIsCheckInDialogOpen] = useState(false)

    const { form, isEditing, invalidate } = useResourceForm<JobCardFormValues, any>({
        schema: jobCardFormSchema,
        defaultValues: DEFAULT_VALUES,
        resourceId,
        initialData,
        queryKey: [JOB_CARD_ROUTES.BY_ID, resourceId],
        initialize: (id) => api.jobCards.show(id),
        mapToFormValues,
    })

    const hasInsurance = form.watch("has_insurance")
    const status = form.watch("status")
    const customer = form.watch("customer")
    const shouldCollectCheckInDetails = status === "check_in"

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: JobCardFormValues) => {
            const payload = mapFormToPayload(values)
            const promise = (isEditing && resourceId
                ? api.jobCards.update(resourceId, payload)
                : api.jobCards.create(payload)) as Promise<any>
            toast.promise(promise, {
                loading: isEditing ? "Updating job card..." : "Creating job card...",
                success: isEditing ? "Job card updated successfully" : "Job card created successfully",
                error: isEditing ? "Failed to update job card" : "Failed to create job card",
            })
            return promise
        },
        onSuccess: () => {
            setIsCheckInDialogOpen(false)
            if (!isEditing) form.reset()
            onSuccess?.()
        },
    })

    const handleSubmit = (values: JobCardFormValues) => {
        if (values.status === "check_in" && !isCheckInDialogOpen) {
            setIsCheckInDialogOpen(true)
            return
        }

        mutate(values)
    }

    const handleCheckInConfirm = () => {
        void form.handleSubmit(handleSubmit)()
    }

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

            <div className="grid grid-cols-1 gap-6 lg:grid-cols-[1fr_360px]">

                {/* ── Left column ── */}
                <div className="space-y-4">
                    <RhfLabelPickerField name="labels" label="Labels" />
                    <RhfTextField name="title" label="Title" placeholder="Job Card 001" required />

                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <RhfCustomerSelectField required name="customer" />
                        <RhfVehicleSelectField required name="vehicle" disabled={!customer?.value} customer_id={customer?.value} />
                    </div>

                    <RhfCheckboxField name="has_insurance" label="Has Insurance Work?" />
                    {hasInsurance && (
                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                            <RhfCustomerSelectField
                                name="insurer"
                                label="Insurer"
                                placeholder="Search insurer..."
                                customerType="Insurer"
                            />
                            <div>
                                <div className="flex items-center justify-between mb-1">
                                    <span className="text-sm font-medium">Insurance Type</span>
                                    <InsuranceTypeCrudDialog />
                                </div>
                                <RhfAsyncSelectField
                                    name="insurance_type"
                                    label=""
                                    placeholder="Select insurance type"
                                    queryKey={[INSURANCE_TYPE_ROUTES.INDEX]}
                                    listFn={() => api.insuranceTypes.list()}
                                    mapOption={(op) => (mapLookupOption(op, 'title'))}
                                    {...STORE_OBJECT}
                                />
                            </div>
                        </div>
                    )}

                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-4">
                        <RhfDateField name="order_date" label="Order Date" />

                        <RhfAutoGenerateField autoFetch name="order_number" label="Order#" placeholder="ORD-001" table="job_cards" />
                        <RhfAutoGenerateField autoFetch name="estimate_number" label="Estimate#" placeholder="EST-001" table="estimates" />
                    </div>

                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <RhfEmployeeSelectField
                            showCreate
                            name="service_writer"
                            label="Service Writer"
                            placeholder="Select service writer"
                            {...STORE_OBJECT}
                        />
                        <RhfEmployeeSelectField
                            showCreate
                            name="primary_technician"
                            label="Primary Technician"
                            placeholder="Select technician"
                            {...STORE_OBJECT}
                        />
                    </div>
                </div>

                {/* ── Right column ── */}
                <div className="space-y-4">
                    <RhfSelectField
                        name="status"
                        label="Status"
                        placeholder="Select status"
                        options={JOB_CARD_STATUS_OPTIONS}
                    />
                    <RhfSelectField
                        name="discount_type"
                        label="Discount Type"
                        placeholder="Select discount type"
                        options={DISCOUNT_TYPE_OPTIONS}
                    />
                    <RhfAsyncSelectField
                        name="tax"
                        label="Tax"
                        placeholder="Select tax rate"
                        queryKey={[TAX_ROUTES.INDEX]}
                        listFn={() => api.taxes.list()}
                        mapOption={(item: any) => ({
                            value: String(item.id),
                            label: item.title ? `${item.title} (${item.rate}%)` : `#${item.id}`,
                        })}
                        {...STORE_OBJECT}
                    />
                    <RhfCustomerRemarksField name="customer_remarks" />
                    <RhfTextareaField name="footer" label="Estimate Footer" placeholder="Thank you for your business." rows={6} />
                    <RhfCheckboxField
                        name="enable_parts_issuing"
                        label="Enable Parts Issuing"
                        description="When off, parts will be auto issued upon authorization. When on, manually request, reserve, and issue parts."
                    />
                    <RhfCheckboxField
                        name="enable_digital_authorisation"
                        label="Enable Digital Authorisation"
                        description="When off, items will be auto authorised. When on, customer approval is required before proceeding."
                    />
                </div>
            </div>

            <div className="mt-6">
                <Button type="submit" variant="default" disabled={isPending}>
                    {isEditing ? <Save /> : <Plus />}
                    {isPending
                        ? (isEditing ? "Updating..." : "Creating...")
                        : shouldCollectCheckInDetails
                            ? "Continue to Check In"
                            : (isEditing ? "Update Job Card" : "Create Job Card")}
                </Button>
            </div>

            <Dialog open={isCheckInDialogOpen} onOpenChange={setIsCheckInDialogOpen}>
                <DialogContent className="sm:max-w-3xl">
                    <DialogHeader>
                        <DialogTitle>Check In Details</DialogTitle>
                        <DialogDescription>
                            Fill the vehicle intake details, then confirm the check in to submit the job card.
                        </DialogDescription>
                    </DialogHeader>

                    <div className="space-y-4">
                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                            <RhfDateField name="check_in_date" label="Check In Date" />
                            <RhfTimeField name="check_in_time" label="Check In Time" />
                        </div>

                        <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
                            <RhfTextField name="km_in" label="KMs IN" placeholder="0" type="number" />
                            <RhfSelectField
                                name="fuel_level"
                                label="Fuel Level"
                                placeholder="Select"
                                options={FUEL_LEVEL_OPTIONS}
                            />
                            <RhfDateField name="start_date" label="Start Date" />
                            <RhfTimeField name="start_time" label="Start Time" />
                        </div>

                        <div className="grid grid-cols-1 gap-4 sm:grid-cols-[1fr_1fr_1fr]">
                            <RhfAsyncSelectField
                                name="department"
                                label="Department"
                                placeholder="Select department"
                                required
                                queryKey={[DEPARTMENT_ROUTES.INDEX]}
                                listFn={() => api.departments.list()}
                                mapOption={mapLookupOption}
                                {...STORE_OBJECT}
                            />
                            <RhfDateField name="delivery_date" label="Delivery Date" />
                            <RhfTimeField name="delivery_time" label="Delivery Time" />
                        </div>
                    </div>

                    <DialogFooter>
                        <Button type="button" variant="outline" onClick={() => setIsCheckInDialogOpen(false)} disabled={isPending}>
                            Cancel
                        </Button>
                        <Button type="button" onClick={handleCheckInConfirm} disabled={isPending}>
                            {isPending ? "Checking In..." : "Check In"}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </Rhform>
    )
}
