"use client"

import { AlertTriangle, Save } from "lucide-react"
import { useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { useQuery } from "@tanstack/react-query"
import { toast } from "sonner"

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,
    RhfAsyncSelectField,
    RhfTextareaField,
} from "@/shared/components/form"
import { useAuthApi } from "@/shared/useApi"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toId } from "@/shared/lib/utils"

import { FirstDayOfWork } from "@garage/api"
import { SETTINGS_ROUTES } from "@garage/api"
import { settingsFormSchema, type SettingsFormValues } from "./settings.schema"

// ── Constants ──

const FIRST_DAY_OPTIONS = FirstDayOfWork.map((d) => ({
    value: d,
    label: d.charAt(0).toUpperCase() + d.slice(1),
}))

const mapLookupOption = (item: any) => ({ value: String(item.id), label: item.name })
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }

// ── Default values ──

const DEFAULT_VALUES: SettingsFormValues = {
    name: "",
    email: "",
    phone: "",
    alternative_phone: "",
    website: "",
    time_zone: "",
    upi_id: "",
    first_day_of_work: "",
    latitude: "",
    longitude: "",
    bank_details: "",
    first_address_line: "",
    second_address_line: "",
    country: null,
    state: null,
    city: "",
    zip_code: "",
    description: "",
    security: "",
    privacy_policy: "",
}

// ── Mapping helpers ──

function mapToFormValues(data: unknown): SettingsFormValues {
    const d = (data as any)?.data ?? data ?? {}
    return {
        name: d.name ?? "",
        email: d.email ?? "",
        phone: d.phone ?? "",
        alternative_phone: d.alternative_phone ?? "",
        website: d.website ?? "",
        time_zone: d.time_zone ?? "",
        upi_id: d.upi_id ?? "",
        first_day_of_work: d.first_day_of_work ?? "",
        latitude: d.latitude ?? "",
        longitude: d.longitude ?? "",
        bank_details: d.bank_details ?? "",
        first_address_line: d.first_address_line ?? "",
        second_address_line: d.second_address_line ?? "",
        country: null,
        state: null,
        city: d.city ?? "",
        zip_code: d.zip_code ?? "",
        description: d.description ?? "",
        security: d.security ?? "",
        privacy_policy: d.privacy_policy ?? "",
    }
}

function mapFormToPayload(values: SettingsFormValues) {
    return {
        name: values.name,
        email: values.email || undefined,
        phone: values.phone || undefined,
        time_zone: values.time_zone || undefined,
        first_day_of_work: values.first_day_of_work || undefined,
        first_address_line: values.first_address_line || undefined,
        country_id: toId(values.country),
        city: values.city || undefined,
    }
}

// ── Component ──

export function SettingsForm() {
    const api = useAuthApi()

    const form = useForm<SettingsFormValues>({
        resolver: zodResolver(settingsFormSchema) as any,
        defaultValues: DEFAULT_VALUES,
    })

    const { data, isLoading } = useQuery({
        queryKey: [SETTINGS_ROUTES.INDEX],
        queryFn: () => api.settings.fetch(),
    })

    useEffect(() => {
        if (!data) return
        const raw = (data as any)?.data
        const record = Array.isArray(raw) ? raw[0] : raw
        if (record) {
            form.reset(mapToFormValues(record))
        }
    }, [data]) // eslint-disable-line react-hooks/exhaustive-deps

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: SettingsFormValues) => {
            const payload = mapFormToPayload(values)
            const promise = api.settings.update(payload)
            toast.promise(promise, {
                loading: "Saving settings...",
                success: "Settings saved successfully",
                error: "Failed to save settings",
            })
            return promise
        },
    })

    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 save settings</AlertTitle>
                    {error.message}
                </Alert>
            )}

            <FieldGroup>
                {/* General Info */}
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField
                        name="name"
                        label="Workshop Name"
                        placeholder="My Workshop"
                        required
                        disabled={isLoading}
                    />
                    <RhfTextField
                        name="email"
                        label="Email"
                        placeholder="workshop@example.com"
                        type="email"
                        disabled={isLoading}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField
                        name="phone"
                        label="Phone"
                        placeholder="+971501234567"
                        type="tel"
                        disabled={isLoading}
                    />
                    <RhfTextField
                        name="alternative_phone"
                        label="Alternative Phone"
                        placeholder="+971509876543"
                        type="tel"
                        disabled={isLoading}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField
                        name="website"
                        label="Website"
                        placeholder="https://example.com"
                        disabled={isLoading}
                    />
                    <RhfTextField
                        name="upi_id"
                        label="UPI ID"
                        placeholder="workshop@upi"
                        disabled={isLoading}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField
                        name="time_zone"
                        label="Time Zone"
                        placeholder="Asia/Dubai"
                        disabled={isLoading}
                    />
                    <RhfSelectField
                        name="first_day_of_work"
                        label="First Day of Work"
                        placeholder="Select day"
                        options={FIRST_DAY_OPTIONS}
                        disabled={isLoading}
                    />
                </div>

                {/* Address */}
                <RhfTextField
                    name="first_address_line"
                    label="Address Line 1"
                    placeholder="Street 10"
                    disabled={isLoading}
                />
                <RhfTextField
                    name="second_address_line"
                    label="Address Line 2"
                    placeholder="Near Central Plaza"
                    disabled={isLoading}
                />

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAsyncSelectField
                        name="country"
                        label="Country"
                        placeholder="Select country"
                        queryKey={["countries"]}
                        listFn={() => api.geo.countries()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                    <RhfAsyncSelectField
                        name="state"
                        label="State"
                        placeholder="Select state"
                        queryKey={["states"]}
                        listFn={() => api.geo.states()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField
                        name="city"
                        label="City"
                        placeholder="Dubai"
                        disabled={isLoading}
                    />
                    <RhfTextField
                        name="zip_code"
                        label="Zip Code"
                        placeholder="00000"
                        disabled={isLoading}
                    />
                </div>

                {/* Location */}
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField
                        name="latitude"
                        label="Latitude"
                        placeholder="25.2048"
                        disabled={isLoading}
                    />
                    <RhfTextField
                        name="longitude"
                        label="Longitude"
                        placeholder="55.2708"
                        disabled={isLoading}
                    />
                </div>

                {/* Other */}
                <RhfTextareaField
                    name="bank_details"
                    label="Bank Details"
                    placeholder="Bank name, account number, IBAN..."
                    disabled={isLoading}
                />
                <RhfTextareaField
                    name="description"
                    label="Description"
                    placeholder="About the workshop..."
                    disabled={isLoading}
                />
                <RhfTextareaField
                    name="security"
                    label="Security Policy"
                    placeholder="Security policy text..."
                    disabled={isLoading}
                />
                <RhfTextareaField
                    name="privacy_policy"
                    label="Privacy Policy"
                    placeholder="Privacy policy text..."
                    disabled={isLoading}
                />

                <div className="flex justify-end">
                    <Button type="submit" disabled={isPending || isLoading}>
                        <Save />
                        {isPending ? "Saving..." : "Save Settings"}
                    </Button>
                </div>
            </FieldGroup>
        </Rhform>
    )
}
