"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, useQueryClient } 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 { RhfImageField } from "@/shared/components/form/fields/rhf-image-field"
import { useAuthApi } from "@/shared/useApi"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toId } from "@/shared/lib/utils"
import { CONSTANTS } from "@/config/constants"

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: "",
    logo: null,
}

// ── 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 ?? "",
        logo: null,
    }
}

function mapFormToPayload(values: SettingsFormValues) {
    return {
        name: values.name,
        email: values.email || undefined,
        phone: values.phone || undefined,
        alternative_phone: values.alternative_phone || undefined,
        website: values.website || undefined,
        time_zone: values.time_zone || undefined,
        upi_id: values.upi_id || undefined,
        first_day_of_work: values.first_day_of_work || undefined,
        latitude: values.latitude || undefined,
        longitude: values.longitude || undefined,
        bank_details: values.bank_details || undefined,
        first_address_line: values.first_address_line || undefined,
        second_address_line: values.second_address_line || undefined,
        country_id: toId(values.country),
        state_id: toId(values.state),
        city: values.city || undefined,
        zip_code: values.zip_code || undefined,
        description: values.description || undefined,
        security: values.security || undefined,
        privacy_policy: values.privacy_policy || undefined,
        logo: values.logo instanceof File ? values.logo : undefined,
    }
}

// ── Component ──

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

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

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

    const existingLogoPath: string | null = (() => {
        const raw = (data as any)?.data
        const record = Array.isArray(raw) ? raw[0] : raw
        const logo = record?.logo
        if (!logo || typeof logo !== "string") return null
        return logo.startsWith("http") ? logo : CONSTANTS.getAssetUrl(`storage/${logo.replace(/^\/+/, "")}`)
    })()

    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) => api.settings.update(mapFormToPayload(values)),
        onSuccess: () => {
            toast.success("Settings saved successfully")
            // Refresh the settings query so the onboarding gate releases once
            // the company info has been filled in.
            queryClient.invalidateQueries({ queryKey: [SETTINGS_ROUTES.INDEX] })
        },
        onError: () => {
            toast.error("Failed to save settings")
        },
    })

    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>
            )}

            <div className="grid gap-6 lg:grid-cols-12">
                {/* Main Content - 8/12 */}
                <div className="lg:col-span-8">
                    <FieldGroup className="space-y-6">
                        {/* General Information Section */}
                        <div>
                            <h3 className="mb-4 text-base font-semibold">General Information</h3>
                            <div className="grid 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="mt-4 grid 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="mt-4 grid 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>

                        {/* Address Section */}
                        <div className="border-t pt-6">
                            <h3 className="mb-4 text-base font-semibold">Address</h3>
                            <RhfTextField
                                name="first_address_line"
                                label="Address Line 1"
                                placeholder="Street 10"
                                disabled={isLoading}
                            />

                            <div className="mt-4">
                                <RhfTextField
                                    name="second_address_line"
                                    label="Address Line 2"
                                    placeholder="Near Central Plaza"
                                    disabled={isLoading}
                                />
                            </div>

                            <div className="mt-4 grid 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="mt-4 grid 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>
                        </div>

                        {/* More Information Section */}
                        <div className="border-t pt-6">
                            <h3 className="mb-4 text-base font-semibold">More Information</h3>
                            <RhfTextareaField
                                name="description"
                                label="Description"
                                placeholder="About the workshop..."
                                disabled={isLoading}
                            />

                            <div className="mt-4">
                                <RhfTextareaField
                                    name="bank_details"
                                    label="Bank Details"
                                    placeholder="Bank name, account number, IBAN..."
                                    disabled={isLoading}
                                />
                            </div>
                        </div>
                    </FieldGroup>
                </div>

                {/* Sidebar - 4/12 */}
                <div className="lg:col-span-4">
                    <FieldGroup className="sticky top-24 space-y-6">
                        {/* Logo Section */}
                        <div className="rounded-lg border bg-card p-4">
                            <h3 className="mb-1 text-base font-semibold">Workshop Logo</h3>
                            <p className="text-muted-foreground mb-3 text-xs">
                                Shown on printed invoices, estimates, job cards and other documents.
                            </p>
                            <RhfImageField
                                name="logo"
                                accept="image/png,image/jpeg,image/jpg,image/webp,image/svg+xml"
                                disabled={isLoading}
                                initialPreviewUrl={existingLogoPath}
                            />
                        </div>

                        {/* Location & Time Section */}
                        <div className="rounded-lg border bg-card p-4">
                            <h3 className="mb-4 text-base font-semibold">Location & Time</h3>
                            
                            <RhfTextField
                                name="latitude"
                                label="Latitude"
                                placeholder="25.2048"
                                disabled={isLoading}
                            />

                            <div className="mt-4">
                                <RhfTextField
                                    name="longitude"
                                    label="Longitude"
                                    placeholder="55.2708"
                                    disabled={isLoading}
                                />
                            </div>

                            <div className="mt-4">
                                <RhfTextField
                                    name="time_zone"
                                    label="Time Zone"
                                    placeholder="Asia/Dubai"
                                    disabled={isLoading}
                                />
                            </div>

                            <div className="mt-4">
                                <RhfSelectField
                                    name="first_day_of_work"
                                    label="First Day of Work"
                                    placeholder="Select day"
                                    options={FIRST_DAY_OPTIONS}
                                    disabled={isLoading}
                                />
                            </div>
                        </div>

                        {/* Policies Section */}
                        <div className="rounded-lg border bg-card p-4">
                            <h3 className="mb-4 text-base font-semibold">Policies</h3>
                            
                            <RhfTextareaField
                                name="security"
                                label="Security Policy"
                                placeholder="Security policy text..."
                                disabled={isLoading}
                            />

                            <div className="mt-4">
                                <RhfTextareaField
                                    name="privacy_policy"
                                    label="Terms and Conditions"
                                    placeholder="Terms and conditions text..."
                                    disabled={isLoading}
                                />
                            </div>
                        </div>

                        {/* Action Button */}
                        <div className="flex flex-col gap-2">
                            <Button 
                                type="submit" 
                                disabled={isPending || isLoading}
                                size="lg"
                                className="w-full"
                            >
                                <Save className="me-2" />
                                {isPending ? "Saving..." : "Save Settings"}
                            </Button>
                        </div>
                    </FieldGroup>
                </div>
            </div>
        </Rhform>
    )
}
