import { Head, useForm, usePage } from '@inertiajs/react'
import { useEffect, useState } from 'react'
import AppLayout from '@/layouts/app-layout'
import IndexPageLayout from '@/components/core/IndexPageLayout'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { ImageOff, Save } from 'lucide-react'
import ImagePicker from '@/components/core/ImagePicker'
import { BreadcrumbItem } from '@/types'
import AvailabilityRulesList from '@/components/(dashboard)/AvailabilityRules/AvailabilityRulesList'
import Icon from '@/components/core/Icon'
import InputField, { TextAreaField } from '@/components/core/InputField'
import { Spinner } from '@/components/ui/spinner'
import { Rule } from '@/types/availabilityRules'
import { toast } from 'sonner'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import AddOnVariant from './AddOnVariant'
import { Separator } from '@/components/ui/separator'
import { AddOnFormProp, AddOnVariantProp, APPLY_ON_TYPE, CALCULATION_TYPE } from '@/types/dashboard/facility'

const MAX_IMAGES = 1 // For meal package only one image/icon



interface BackendAddOn extends Omit<AddOnFormProp, "images" | 'availabilityRules'> {
    id: number;
    images: { id: number; url: string; file_size: string; role: string; sort_order: number }[];
    availability_rules: Rule[]
}


type AddOnPageProps = {
    addon?: BackendAddOn,
    mode?: 'create' | 'edit' | 'view',

}

type ImageProp = { id: number; url: string, file_size: string }


export default function AddOnPage() {

    const { addon, mode = 'create' } = usePage<AddOnPageProps>().props

    console.log(addon);



    const { data, setData, post, put, processing, errors } = useForm<AddOnFormProp>({
        sort_order: addon?.sort_order || 0,
        title: addon?.title || '',
        description: addon?.description || '',
        price: addon?.price || 0,
        currency: addon?.currency || 'LKR',
        unit: addon?.unit || 1,
        min_quantity: addon?.min_quantity || null,
        max_quantity: addon?.max_quantity || null,
        allow_qantity: addon?.allow_qantity || false,
        min_guests: addon?.min_guests || null,
        max_guests: addon?.max_guests || null,
        allow_guests: addon?.allow_guests || false,
        calculation_type: addon?.calculation_type || 'per_booking',
        scope: addon?.scope || 'all_rooms',
        apply_on: addon?.apply_on || 'booking',
        tag: addon?.tag || '',
        icon: addon?.icon || '',
        icon_url: addon?.icon_url || '',
        is_variant: addon?.is_variant || false,
        is_published: addon?.is_published ?? true,
        default_active: addon?.default_active ?? true,
        images: addon?.images?.map(img => ({
            id: img.id,
            role: img.role,
            sort_order: img.sort_order,
        })) || [],
        availabilityRules: addon?.availability_rules || [],
        variants: addon?.variants || [],
    })

    const [images, setImages] = useState<ImageProp[]>([])
    const [icon, setIcon] = useState<string>('')


    const view = mode === 'view'


    // Create the path on top
    let breadcrumbs: BreadcrumbItem[] = [
        {
            title: 'Add-Ons',
            href: '/dashboard/add-ons',
        },
        {
            title: 'Create New',
            href: '/dashboard/add-ons/create',
        },
    ];


    if (mode !== 'create') {
        breadcrumbs.pop()
        breadcrumbs.push({
            title: `#${addon?.id}`,
            href: `/dashboard/add-ons/${addon?.id}`,
        })
        if (mode === 'edit') {
            breadcrumbs.push({
                title: `edit`,
                href: `/dashboard/add-ons/${addon?.id}/edit`,
            })
        }
    }



    const imageHandler = (selected: ImageProp[]) => {
        setImages(prev => [...prev, ...selected])
        setData('icon', '')
    }

    const iconHandler = (icon: string) => {
        setIcon(icon)
        setData('images', [])
        setImages([])

        setData('icon_url', '')
        setData('icon', icon)
    }

    // Submit the data
    const submit = () => {
        if (mode === 'create') {
            post('/dashboard/add-ons', { onSuccess: () => toast.success('Sucsessfuly Created Add-On'), onError: (error) => toast.error(error.message || 'Something went wrong..!') })
        } else if (mode === 'edit' && addon) {
            put(`/dashboard/add-ons/${addon.id}`, { onSuccess: () => toast.success('Sucsessfuly Updated the Add-On'), onError: (error) => toast.error(error.message || 'Something went wrong..!') })
        }

    }


    // Update images and icon URL when images change
    useEffect(() => {
        const formattedImages = images.map((img, index) => ({
            id: img.id,
            role: 'icon',
            sort_order: index
        }))

        setData('images', formattedImages)
        setData('icon_url', images[0]?.url)
    }, [images])

    // Load data from backend when editing/viewing
    useEffect(() => {
        if (!addon) return
        setData({
            ...data,
            // title: addon.title,
            // description: addon.description,
            // price: addon.price,
            // unit: addon.unit,
            // currency: addon.currency,
            // calculation_type: addon.calculation_type,
            // scope: addon.scope,
            // tag: addon.tag,
            // icon: addon.icon,
            // icon_url: addon.icon_url,
            // is_variant: addon.is_variant,
            // is_published: addon.is_published,
            // default_active: addon.default_active,
            // images: addon.images.map(img => ({
            //     id: img.id,
            //     role: img.role,
            //     sort_order: img.sort_order
            // })),
            availabilityRules: addon.availability_rules,
            // variants: addon.variants
        })

    }, [addon])


    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={mode === 'view' ? `Add-On #${addon?.id}` : mode === 'edit' ? `Edit Add-On` : "Create Add-On"} />
            <IndexPageLayout title={'Add-On'} path='/dashboard/add-ons' id={addon?.id} mode={mode} >


                <div className="flex flex-col lg:flex-row gap-4">
                    <div className='space-y-4' >

                        <div className="border p-6 rounded-lg bg-card space-y-4 flex-1 h-fit max-w-xl">


                            {/* Images */}
                            <div className="flex gap-4 w-full">

                                <ImagePicker iconTab disabled={mode === 'view'} defaultTab='icons' selected={images} onSelect={imageHandler} icon={icon} onSelectIcon={iconHandler} max={MAX_IMAGES} className='border-none'>
                                    {data.icon && <div className='border-2 rounded-sm aspect-square justify-center group items-center flex flex-col gap-2 hover:border-blue-400 hover:bg-blue-50 hover:dark:bg-blue-950 h-14 w-fit p-2'>
                                        <Icon icon={data.icon} className="w-8 h-8 text-blue-400 group-hover:text-blue-400" />
                                    </div>}

                                    {data.icon_url && <div className='border-2 rounded-sm text-xs aspect-square h-14 p-1.5 flex justify-center items-center hover:border-blue-400'>
                                        <img src={data.icon_url} className="object-cover rounded-sm" alt="Meal Package" />
                                    </div>}

                                    {(!data.icon && !data.icon_url) && <div className='border-2 rounded-sm aspect-square justify-center group items-center flex flex-col gap-1 hover:border-blue-400 hover:bg-blue-50 hover:dark:bg-blue-950 h-14 w-fit'>
                                        <ImageOff className="w-8 h-8 text-neutral-400 group-hover:text-blue-400" />
                                    </div>}
                                </ImagePicker>

                                <InputField label='Title' value={data.title} onChange={value => setData('title', value)} disabled={view || processing} error={errors.title} />
                            </div>

                            {/* Information */}
                            <div className="flex flex-col gap-4">
                                <InputField label='Tag' value={data.tag} onChange={value => setData('tag', value)} disabled={view || processing} error={errors.tag} helperMsg='As example "Popular"' />

                                <TextAreaField label='Description' maxLength={100} value={data.description} onChange={(value) => setData('description', value)} placeholder='Write a small description' disabled={view || processing} error={errors.description} />

                                <div className="flex gap-4">
                                    <div className="space-y-2  flex-1">
                                        <Label>Calculation Type</Label>
                                        <Select
                                            disabled={view || processing}
                                            value={data.calculation_type}
                                            onValueChange={(value: CALCULATION_TYPE) => setData("calculation_type", value)}
                                        >
                                            <SelectTrigger className='w-full'  >
                                                <SelectValue placeholder='Select a type' />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="per_booking">Per Booking</SelectItem>
                                                <SelectItem value="per_room">Per Room</SelectItem>
                                                <SelectItem value="per_room_per_night">Per Room Per Night</SelectItem>
                                                <SelectItem value="per_night">Per Night</SelectItem>
                                                <SelectItem value="per_person">Per Person</SelectItem>
                                                <SelectItem value="per_person_per_night">Per Person Per Night</SelectItem>
                                                <SelectItem value="per_quantity">Per Quantity</SelectItem>
                                            </SelectContent>
                                        </Select>
                                        {errors.calculation_type && <p className='text-red-600 text-sm'>{errors.calculation_type}</p>}
                                    </div>
                                    <div className="space-y-2  flex-1">
                                        <Label>Scope</Label>
                                        <Select
                                            disabled={view || processing}
                                            value={data.scope}
                                            onValueChange={(value: 'booking' | 'all_rooms' | 'room_category' | 'room') => setData("scope", value)}
                                        >
                                            <SelectTrigger className='w-full' >
                                                <SelectValue placeholder='Select a type' />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="booking">Apply Booking</SelectItem>
                                                <SelectItem value="all_rooms">Apply to All Rooms</SelectItem>
                                                <SelectItem value="room_category">Category Specific</SelectItem>
                                                <SelectItem value="room">Room Specific</SelectItem>
                                            </SelectContent>
                                        </Select>
                                        {errors.scope && <p className='text-red-600 text-sm'>{errors.scope}</p>}
                                    </div>
                                </div>

                                <div className="flex gap-4">
                                    <div className="space-y-2  flex-1">
                                        <Label>Apply On</Label>
                                        <Select
                                            disabled={view || processing}
                                            value={data.scope}
                                            onValueChange={(value: APPLY_ON_TYPE) => setData("apply_on", value)}
                                        >
                                            <SelectTrigger className='w-full' >
                                                <SelectValue placeholder='Select a type' />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="booking">Apply On Booking</SelectItem>
                                                <SelectItem value="check_in">Apply When check-In</SelectItem>
                                                <SelectItem value="check_out">Apply When check-Out</SelectItem>
                                                <SelectItem value="entire_stay">Entire Stay</SelectItem>
                                                <SelectItem value="dont_apply">Any Day</SelectItem>
                                            </SelectContent>
                                        </Select>
                                        {errors.apply_on && <p className='text-red-600 text-sm'>{errors.apply_on}</p>}
                                    </div>
                                    <InputField label='Sort Order' type='number' value={data.sort_order} onChange={value => setData('sort_order', Number(value))} helperMsg='Default Sort Order of View' disabled={view || processing} error={errors.sort_order} />
                                </div>

                                <div className="flex gap-4">
                                    <InputField label='Price' type='number' value={data.price} onChange={value => setData('price', Number(value))} startAddon={data.currency} helperMsg='Default price per night per persion' disabled={view || processing} error={errors.price} />
                                    <InputField label='Unit' type='number' value={data.unit} onChange={value => setData('unit', Number(value))} disabled={view || processing} error={errors.unit} />
                                </div>

                                <div className="flex gap-4">
                                    <InputField label='Min Guests' type='number' value={data.min_guests || ''} onChange={value => setData('min_guests', Number(value))} helperMsg='Min Guests that can select' disabled={view || processing} error={errors.min_guests} />
                                    <InputField label='Max Guests' type='number' value={data.max_guests || ''} onChange={value => setData('max_guests', Number(value))} helperMsg='Max Guests that can select' disabled={view || processing} error={errors.max_guests} />
                                    <div className="flex items-center gap-2">
                                        <Checkbox checked={data.allow_guests} onCheckedChange={value => setData('allow_guests', Boolean(value))} disabled={view || processing} />
                                        <Label className='max-w-20'>Allow Enter Guests</Label>
                                    </div>
                                </div>

                                <div className="flex gap-4">
                                    <InputField label='Min quantity' type='number' value={data.min_quantity || ''} onChange={value => setData('min_quantity', Number(value))} helperMsg='Min quantity that can select' disabled={view || processing} error={errors.min_quantity} />
                                    <InputField label='Max quantity' type='number' value={data.max_quantity || ''} onChange={value => setData('max_quantity', Number(value))} helperMsg='Max quantity that can select' disabled={view || processing} error={errors.max_quantity} />
                                    <div className="flex items-center gap-2">
                                        <Checkbox checked={data.allow_qantity} onCheckedChange={value => setData('allow_qantity', Boolean(value))} disabled={view || processing} />
                                        <Label className='max-w-20'>Allow Enter Quantity</Label>
                                    </div>
                                </div>
                                <Separator />
                                <div className="flex items-center gap-2">
                                    <Checkbox checked={data.is_published} onCheckedChange={value => setData('is_published', Boolean(value))} disabled={view || processing} />
                                    <Label>Published</Label>
                                </div>
                                <div className="flex items-center gap-2">
                                    <Checkbox checked={data.default_active} onCheckedChange={value => setData('default_active', Boolean(value))} disabled={view || processing} />
                                    <Label>Active by default</Label>
                                </div>
                                <div className="flex items-center gap-2">
                                    <Checkbox checked={data.is_variant} onCheckedChange={value => setData('is_variant', Boolean(value))} disabled={view || processing} />
                                    <Label>Variant Add-On</Label>
                                </div>
                            </div>

                            {
                                data.is_variant ? <>
                                    <Separator />
                                    <AddOnVariant view={view} disabled={view || processing} variants={data.variants} setData={setData} />
                                </> : null
                            }

                            {errors.variants ? <p className='text-red-600 text-sm'>{errors.variants}</p> : null}


                            {!view && <div className='w-full flex justify-end'>
                                <Button type="button" onClick={submit} disabled={processing}>{mode === 'edit' ? <>{processing ? <><Spinner /> Saving...</> : <><Save /> Save Changes</>}</> : <>{processing ? <><Spinner /> Creating...</> : <>Create Add-On</>}</>}</Button>
                            </div>
                            }

                        </div>



                    </div>
                    {
                        mode !== 'create' &&
                        <AvailabilityRulesList defaultActivity={data.default_active} rules={data.availabilityRules} type='AddOn' id={addon?.id} edit={mode === 'edit'} />
                    }
                </div>
            </IndexPageLayout >
        </AppLayout >
    )
}
