

import Icon from '@/components/core/Icon'
import ImagePicker from '@/components/core/ImagePicker'
import InputField, { TextAreaField } from '@/components/core/InputField'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Spinner } from '@/components/ui/spinner'
import { AddOnFormProp, AddOnVariantProp } from '@/types/dashboard/facility'
import { SetDataAction } from '@inertiajs/react'
import { ClipboardClock, ImageOff, PenBox, Pencil, Save, Trash2 } from 'lucide-react'
import React, { Dispatch, SetStateAction, useState } from 'react'

type AddOnVariantInput = {
    view: boolean,
    disabled: boolean,
    variants: AddOnVariantProp[],
    setData: SetDataAction<AddOnFormProp>
}


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

type AddOnVariantInputs = {
    open: boolean,
    variant: AddOnVariantProp
    setOpen: Dispatch<SetStateAction<boolean>>
    setVariant: Dispatch<SetStateAction<AddOnVariantProp>>,
    handleSave: () => void
}

function AddOnVariantDialog({ open, setOpen, variant, setVariant, handleSave }: AddOnVariantInputs) {


    const edit = variant.id !== 'new'

    console.log(variant);


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

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

    const iconHandler = (icon: string) => {
        setIcon(icon)
        setVariant(prev => ({ ...prev, icon }))
        setImages([])

        setChangedData('icon_url', '')
        setChangedData('icon', icon)
    }

    // Changes Handler
    const setChangedData = (name: string, value: string | number) => {
        setVariant({
            ...variant,
            [name]: value
        })
    }


    // Close Hanlder
    const handleClose = () => {
        setVariant({
            id: 'new',
            sort_order: 0,
            title: '',
            description: '',
            price: 0,
            currency: 'LKR',
            unit: 1,
            min_quantity: null,
            max_quantity: null,
            min_guests: null,
            max_guests: null,
            icon: '',
            icon_url: '',
            is_active: true,
        })
        setOpen(false)
    }


    return <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild>
            <Button variant='outline'><ClipboardClock />Add New Variant</Button>
        </DialogTrigger>
        <DialogContent>
            <DialogHeader>
                <DialogTitle>
                    {edit ? 'Edit Variant' : 'Add New Variant'}
                </DialogTitle>
            </DialogHeader>

            <div className="space-y-4 mb-4">

                <div className="flex gap-4 w-full">

                    <ImagePicker iconTab defaultTab='icons' selected={images} onSelect={imageHandler} icon={icon} onSelectIcon={iconHandler} max={1} className='border-none'>
                        {variant?.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={variant.icon} className="w-8 h-8 text-blue-400 group-hover:text-blue-400" />
                        </div>}

                        {variant?.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={variant.icon_url} className="object-cover rounded-sm" alt="Meal Package" />
                        </div>}

                        {(!variant?.icon && !variant?.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" type="text" placeholder="Enter Title" value={variant?.title || ''} onChange={(value) => setChangedData("title", value)} />
                </div>
                <TextAreaField label="Description" placeholder="Enter Description" maxLength={100} value={variant?.description || ''} onChange={(value) => setChangedData("description", value)} />

                <div className='flex gap-4'>
                    <InputField label="Price" type="number" placeholder="Enter Price" startAddon='LKR' value={variant?.price || 0} onChange={(value) => setChangedData("price", Number(value))} />
                    <InputField label="Sort Order" type="number" placeholder="Enter Sort Order" value={variant?.sort_order || 0} onChange={(value) => setChangedData("sort_order", Number(value))} />
                </div>
                <div className="flex gap-4">
                    <InputField label='Min Guests' placeholder="Enter Min Guests" type='number' value={variant?.min_guests || ''} onChange={value => setChangedData('min_guests', Number(value))} />
                    <InputField label='Max Guests' placeholder="Enter Max Guests" type='number' value={variant?.max_guests || ''} onChange={value => setChangedData('max_guests', Number(value))} />
                </div>
                <div className="flex gap-4">
                    <InputField label='Min quantity' placeholder="Enter Min quantity" type='number' value={variant?.min_quantity || ''} onChange={value => setChangedData('min_quantity', Number(value))} />
                    <InputField label='Max quantity' placeholder="Enter Max quantity" type='number' value={variant?.max_quantity || ''} onChange={value => setChangedData('max_quantity', Number(value))} />
                </div>
            </div>

            <DialogFooter>
                <Button type="button" variant="outline" onClick={handleClose}  > Cancel </Button>
                <Button type="button" onClick={() => { handleSave(); handleClose() }} > <Save /> Save Variant </Button>
            </DialogFooter>
        </DialogContent>
    </Dialog>
}

export default function AddOnVariant({ view, disabled, variants, setData }: AddOnVariantInput) {


    const [openVariant, setOpenVariant] = useState(false)
    const [variant, setVariant] = useState<AddOnVariantProp>({
        id: 'new',
        sort_order: 0,
        title: '',
        description: '',
        price: 0,
        currency: 'LKR',
        unit: 1,
        min_quantity: null,
        max_quantity: null,
        min_guests: null,
        max_guests: null,
        icon: '',
        icon_url: '',
        is_active: true,
    })

    // 🔹 Save (Add or Update)
    const handleSave = () => {
        // CREATE
        if (variant.id === 'new') {
            const newVariant = {
                ...variant,
                id: ('new_' + Date.now().toString()) // temporary id
            }

            setData('variants', [...variants, newVariant])
        }
        // UPDATE
        else {
            const updated = variants.map(v =>
                v.id === variant.id ? variant : v
            )

            setData('variants', updated)
        }
    }

    // 🔹 Open Edit
    const handleEdit = (index: number) => {
        setVariant(variants[index])
        setOpenVariant(true)
    }

    // 🔹 Delete
    const handleDelete = (index: number) => {
        setData('variants', variants.filter((_, i) => i !== index))
    }

    return (
        <div className="space-y-4">
            <div className="flex justify-between items-center bg-primary">
                <h3 className="font-semibold">Variants</h3>
            </div>

            {variants?.length === 0 && (
                <p className="text-sm text-muted-foreground">
                    No variants added
                </p>
            )}

            {variants.map((v, index) => (
                <div key={v.id} className="flex justify-between gap-2">

                    <div className='w-fit'>
                        {v?.icon && <div className='border-2 rounded-sm aspect-square justify-center group items-center flex flex-col gap-2 h-10 w-fit p-2'>
                            <Icon icon={v.icon} className="w-6 h-6 text-blue-400 " />
                        </div>}

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

                        {(!v?.icon && !v?.icon_url) && <div className='border-2 rounded-sm aspect-square justify-center group items-center flex flex-col gap-1 h-10 w-fit'>
                            <ImageOff className="w-6 h-6 text-neutral-400 " />
                        </div>}
                    </div>
                    <div className='flex-1 flex justify-between'>
                        <div>
                            <p className="font-medium text-sm">
                                {v.title} | {v.max_guests} max | {v.currency} {v.price}
                            </p>
                            <p className="text-sm">{v.description}</p>
                        </div>
                        {
                            !view && <div className="flex gap-2">
                                <Button type="button" size="icon-sm" className='text-primary' variant='outline' onClick={() => handleEdit(index)} ><PenBox /></Button>
                                <Button type="button" size="icon-sm" className='text-destructive' variant="outline" onClick={() => handleDelete(index)}  ><Trash2 /></Button>
                            </div>
                        }

                    </div>
                </div>
            ))}
            {
                !view &&
                <AddOnVariantDialog
                    open={openVariant}
                    setOpen={setOpenVariant}
                    variant={variant}
                    setVariant={setVariant}
                    handleSave={handleSave}
                />

            }
        </div>
    )
}