

import { ImageIconBox } from '@/components/core/Icon'
import InputField, { TextAreaField } from '@/components/core/InputField'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { SetDataAction } from '@inertiajs/react'
import { ForkKnifeIcon, GripVertical, PenBox, Save, Trash2 } from 'lucide-react'
import { Dispatch, SetStateAction, useEffect, useState } from 'react'
import { toast } from 'sonner'
import DragSortGeneric from './SortableItem'
import { DialogDescription } from '@radix-ui/react-dialog'
import { MealPackageForm, MealPackageVariantType } from '@/types/dashboard/meal-package'
import IconOrImageSelector from '@/components/core/IconOrImageSelector'
import AvailabilityRulesList from '@/components/(dashboard)/AvailabilityRules/AvailabilityRulesList'
import { SystemCurrencyType } from '@/types/dashboard/currency'

type VariantInput = {
    view: boolean,
    disabled: boolean,
    variants: MealPackageVariantType[],
    setData: SetDataAction<MealPackageForm>
    defaultAvailability: boolean
    system_currency: SystemCurrencyType
}


type VariantInputs = {
    open: boolean,
    variant: MealPackageVariantType
    setOpen: Dispatch<SetStateAction<boolean>>
    setVariant: Dispatch<SetStateAction<MealPackageVariantType>>,
    handleSave: () => void
    system_currency: SystemCurrencyType
}

function VariantDialog({ open, setOpen, variant, setVariant, handleSave, system_currency }: VariantInputs) {


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

    const [errors, setErrors] = useState<Record<string, string>>({})


    // Changes Handler
    const setChangedData = (name: string, value: string | number | boolean) => {
        console.log('Checged', name, value);

        setVariant(prev => ({
            ...prev,
            [name]: value
        }))
    }

    const validate = () => {
        const newErrors: Record<string, string> = {}

        if (!variant.title.trim()) {
            newErrors.title = "Title is required"
        }

        if (!variant.price || variant.price <= 0) {
            newErrors.price = "Price must be greater than zero"
        }

        if (!variant.unit || variant.unit < 1) {
            newErrors.unit = "Unit must be at least 1"
        }


        setErrors(newErrors)

        return Object.keys(newErrors).length === 0
    }

    const handleSubmit = () => {
        if (!validate()) {
            toast.error('Please check input feilds again!.')
            return
        }

        handleClose()
        handleSave()
        setErrors({})
    }

    // Close Hanlder
    const handleClose = () => {
        setVariant({
            id: 'new',
            sort_order: 0,
            title: '',
            description: '',
            price: 0,
            unit: 1,
            is_icon: true,
            icon_value: '',
            is_published: true,
            default_availability: true,
            availability_rules: []
        })
        setOpen(false)
    }


    useEffect(() => {
        setErrors({})
    }, [open])


    return <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild>
            <Button variant='outline' className='place-self-end'><ForkKnifeIcon />Add New Variant</Button>
        </DialogTrigger>
        <DialogContent>
            <DialogHeader>
                <DialogTitle>
                    {edit ? 'Edit Variant' : 'Add New Variant'}
                </DialogTitle>
                <DialogDescription className='hidden' />
            </DialogHeader>

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

                <div className="flex gap-4 w-full">
                    <IconOrImageSelector value={variant.icon_value} is_icon={variant.is_icon} onChangeType={value => setChangedData('is_icon', value)} onChangeValue={value => setChangedData('icon_value', value)} />

                    <InputField label="Title" type="text" value={variant?.title || ''} onChange={(value) => setChangedData("title", value)} error={errors.title} />
                </div>
                <TextAreaField label="Description" maxLength={100} value={variant?.description || ''} onChange={(value) => setChangedData("description", value)} error={errors.description} />

                <div className='flex gap-4'>
                    <InputField label="Price" type="number" startAddon={system_currency} value={Number(variant?.price) || ''} onChange={(value) => setChangedData("price", Number(value))} error={errors.price} />
                    <InputField label="Unit" type="number" min={1} value={variant?.unit || ''} onChange={(value) => setChangedData("unit", Number(value))} error={errors.unit} />
                </div>
                <div className='flex gap-4 flex-col'>
                    <div className="flex items-center gap-2">
                        <Checkbox checked={variant.default_availability} onCheckedChange={value => setChangedData('default_availability', Boolean(value))} />
                        <Label>Available by default</Label>
                    </div>
                    <div className="flex-1 flex items-center gap-2">
                        <Checkbox checked={variant.is_published} onCheckedChange={value => setChangedData('is_published', Boolean(value))} />
                        <Label>Published</Label>
                    </div>
                </div>
            </div>

            <DialogFooter>
                <Button type="button" variant="outline" onClick={handleClose}  > Cancel </Button>
                <Button type="button" disabled={!open} onClick={handleSubmit} > <Save /> Save Variant </Button>
            </DialogFooter>
        </DialogContent>
    </Dialog>
}

export default function MealPackageVariant({ view, disabled, variants, setData, defaultAvailability, system_currency }: VariantInput) {


    const [openVariant, setOpenVariant] = useState(false)
    const [variant, setVariant] = useState<MealPackageVariantType>({
        id: 'new',
        sort_order: 0,
        title: '',
        description: '',
        price: 0,
        unit: 1,
        is_icon: true,
        icon_value: '',
        is_published: true,
        default_availability: !defaultAvailability,
        availability_rules: [],
    })

    // 🔹 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 = (item: MealPackageVariantType) => {
        setVariant(item)
        setOpenVariant(true)
    }

    // 🔹 Delete
    const handleDelete = (item: MealPackageVariantType) => {
        setData('variants', variants.filter((_) => _.id !== item.id))
    }

    return (
        <div className="space-y-4 bg-card p-4 rounded-sm w-full border">
            <div className="border-b pb-2 ">
                <h3 className="font-semibold">Variants</h3>
            </div>

            {variants?.length === 0 && (
                <div className="flex flex-col items-center justify-center gap-2 py-6 text-center text-muted-foreground">
                    <ForkKnifeIcon className="h-8 w-8 opacity-60" />

                    <p className="text-sm font-medium">
                        No meal variants yet
                    </p>

                    <p className="text-xs max-w-xs">
                        Add variants like <span className="font-medium">Vegetarian</span>,
                        <span className="font-medium"> Vegan</span>, or
                        <span className="font-medium"> Seafood</span> so guests can choose their meal preference.
                    </p>
                </div>
            )}

            <DragSortGeneric
                items={variants}
                setItems={(items) => setData("variants", items)}
                idGetter={(item) => (item.id || '').toString()}
                sortBy='sort_order'
                disabled={view || disabled}
                renderItem={(v, dragHandle) => (
                    <div className="flex items-center gap-2 p-2 border rounded-sm bg-card">
                        {!view && <div {...dragHandle.attributes} {...dragHandle.listeners} className="cursor-grab text-gray-400">
                            <GripVertical size={18} />
                        </div>}
                        <div className="flex justify-between items-center gap-2 w-full">
                            <ImageIconBox is_icon={v.is_icon} value={v.icon_value} />
                            <div className='flex-1 flex justify-between items-center'>
                                <div>
                                    <p className="font-medium text-sm">
                                        {v.title} | {system_currency} {Number(v.price).toLocaleString()}
                                    </p>
                                    <p className="text-sm text-neutral-700 truncate max-w-64">{v.description}</p>
                                </div>
                                <div className="flex gap-2">
                                    {typeof v.id !== 'string' && <AvailabilityRulesList defaultAvailability={v.default_availability} rules={v.availability_rules} type='MealPackageVariant' id={v?.id} edit={!view} title={v.title} />}

                                    {!view && <><Button type="button" size="icon-sm" className='hover:text-primary' variant='outline' onClick={() => handleEdit(v)} ><PenBox /></Button>
                                        <Button type="button" size="icon-sm" className='text-destructive' variant="outline" onClick={() => handleDelete(v)}  ><Trash2 /></Button></>}
                                </div>

                            </div>
                        </div>
                    </div>
                )}
            />

            {
                !view &&
                <VariantDialog
                    open={openVariant}
                    setOpen={setOpenVariant}
                    variant={variant}
                    setVariant={setVariant}
                    handleSave={handleSave}
                    system_currency={system_currency}
                />

            }
        </div>
    )
}