
import InputField, { DateInput, WeekdaySelector } from '@/components/core/InputField'
import ItemSelector from '@/components/core/ItemSelector'
import { Button } from '@/components/ui/button'
import {
    Dialog,
    DialogClose,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger
} from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Spinner } from '@/components/ui/spinner'
import { PriceModifier, RoomCategoryItem, RoomItem } from '@/types/price-modifire'
import { useForm } from '@inertiajs/react'
import { CirclePlus, Info, Save } from 'lucide-react'
import { Dispatch, SetStateAction, useEffect } from 'react'
import { toast } from 'sonner'

type FormProp = {
    id?: number
    name: string
    operation: 'add' | 'subtract'
    calculation: 'flat' | 'percent'
    value: number
    type: 'all' | 'weekday' | 'weekend' | 'custom' | 'holiday'
    custom_days?: number[]
    start_date?: string | null
    end_date?: string | null
    priority: number,
    categories: number[],
    rooms: number[]
}

type MakerProp = {
    modifier: PriceModifier | null
    setModifier: Dispatch<SetStateAction<PriceModifier | null>>
    open: boolean
    setOpen: Dispatch<SetStateAction<boolean>>
    roomCategories: RoomCategoryItem[];
    rooms: RoomItem[];
    view: boolean
}

export default function PriceModifierMaker({ modifier, setModifier, open, setOpen, rooms, roomCategories, view }: MakerProp) {


    const { data, setData, post, put, processing, reset, errors, clearErrors } = useForm<FormProp>({
        name: '',
        operation: 'add',
        calculation: 'flat',
        value: 0,
        type: 'all',
        custom_days: [0, 1, 2, 3, 4, 5, 6],
        start_date: '',
        end_date: '',
        priority: 0,
        categories: [],
        rooms: []
    })

    const edit = modifier !== null

    const submit = () => {
        if (edit) {
            put(`/dashboard/price-modifiers/${modifier?.id}`, {
                onSuccess: () => {
                    toast.success('Successfully updated modifier')
                    handleClose()
                }
                , onError: (error) => toast.error(error.message || 'Please check again!')
            })
        } else {
            post('/dashboard/price-modifiers', {
                onSuccess: () => {
                    toast.success('Successfully created modifier')
                    handleClose()
                }
                , onError: (error) => toast.error(error.message || 'Please check again!')
            })
        }
    }

    const handleClose = () => {
        setOpen(false)
        setModifier(null)
        reset()
        clearErrors()
    }


    const handleTypeChange = (value: "all" | "weekday" | "weekend" | "custom" | "holiday") => {

        setData("type", value)

        if (value === "weekday") {
            setData("custom_days", [0, 1, 2, 3, 4])
        }

        else if (value === "weekend") {
            setData("custom_days", [5, 6])
        }

        else if (value === "all") {
            setData("custom_days", [0, 1, 2, 3, 4, 5, 6])
        }

        else if (value === "custom") {
            setData("custom_days", [])
        }

        else if (value === "holiday") {
            setData("custom_days", [])
        }
    }


    const detectTypeFromDays = (days: number[]) => {

        const sorted = [...days].sort()

        let value: "all" | "weekday" | "weekend" | "custom" | "holiday" = 'custom'
        if (JSON.stringify(sorted) === JSON.stringify([0, 1, 2, 3, 4, 5, 6])) value = "all"
        if (JSON.stringify(sorted) === JSON.stringify([0, 1, 2, 3, 4])) value = "weekday"
        if (JSON.stringify(sorted) === JSON.stringify([5, 6])) value = 'weekend'


        setData("type", value)
        setData('custom_days', days)
    }

    useEffect(() => {
        if (!modifier) return

        setData({
            name: modifier.name,
            operation: modifier.operation,
            calculation: modifier.calculation,
            value: modifier.value,
            type: modifier.type,
            custom_days: modifier.custom_days ?? [],
            start_date: modifier.start_date ?? '',
            end_date: modifier.end_date ?? '',
            priority: modifier.priority,
            categories: modifier.categories ?? [],
            rooms: modifier.rooms ?? []
        })
    }, [modifier])

    useEffect(() => {
        if (!open) handleClose()
    }, [open])

    return (
        <Dialog open={open} onOpenChange={setOpen} >
            <DialogTrigger asChild>
                <Button variant='outline'>
                    <CirclePlus /> Add Modifier
                </Button>
            </DialogTrigger>

            <DialogContent className='min-w-4xl'>

                <DialogHeader>
                    <DialogTitle>{edit ? (view ? `#${modifier.id}` : 'Edit') : 'Create'} Price Modifier</DialogTitle>
                    <DialogDescription>
                        Modify room prices dynamically based on rules like weekends, holidays, or custom days.
                    </DialogDescription>
                </DialogHeader>

                <div className='flex gap-6 '>
                    <div className='flex-3 space-y-4'>
                        <div className="flex gap-4">

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


                        </div>
                        <div className="flex gap-4">

                            <div className="flex-1 space-y-2">
                                <Label>Operation</Label>
                                <Select
                                    value={data.operation}
                                    onValueChange={(value: 'add' | 'subtract') => setData('operation', value)}
                                    disabled={processing || view}
                                >
                                    <SelectTrigger className='w-full'>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="add">add (+)</SelectItem>
                                        <SelectItem value="subtract">Subtract (-)</SelectItem>
                                    </SelectContent>
                                </Select>
                                {errors.operation && <p className='text-red-600 text-sm'>{errors.operation}</p>}
                            </div>

                            <div className="flex-1 space-y-2">
                                <Label>Calculation</Label>
                                <Select
                                    value={data.calculation}
                                    onValueChange={(value: 'flat' | 'percent') => setData('calculation', value)}
                                    disabled={processing || view}
                                >
                                    <SelectTrigger className='w-full'>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="flat">Flat</SelectItem>
                                        <SelectItem value="percent">Percent</SelectItem>
                                    </SelectContent>
                                </Select>
                                {errors.calculation && <p className='text-red-600 text-sm'>{errors.calculation}</p>}
                            </div>

                            <InputField
                                label='Value'
                                type='number'
                                value={data.value.toString()}
                                onChange={value => setData('value', Number(value))}
                                error={errors.value}
                                disabled={processing || view}
                                className='flex-2'
                            />

                        </div>


                        <div className="flex gap-4">
                            <DateInput label='Start Date' value={data.start_date} onChange={value => setData('start_date', value)} error={errors.start_date} disabled={processing || view} />
                            <DateInput label='End Date' value={data.end_date} onChange={value => setData('end_date', value)} error={errors.end_date} disabled={processing || view} />
                        </div>

                        <div className="flex gap-4">

                            <div className="flex-1 space-y-2">
                                <Label>Type</Label>
                                <Select
                                    disabled={processing || view}
                                    value={data.type}
                                    onValueChange={handleTypeChange}
                                >
                                    <SelectTrigger className='w-full'>
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">All Days</SelectItem>
                                        <SelectItem value="weekday">Weekdays</SelectItem>
                                        <SelectItem value="weekend">Weekends</SelectItem>
                                        <SelectItem value="custom">Custom Days</SelectItem>
                                        {/* <SelectItem value="holiday">Holiday</SelectItem> */}
                                    </SelectContent>
                                </Select>
                                {errors.type && <p className='text-red-600 text-sm'>{errors.type}</p>}
                            </div>

                            <InputField
                                label='Priority'
                                type='number'
                                value={data.priority.toString()}
                                onChange={value => setData('priority', Number(value))}
                                disabled={processing || view}
                            />

                        </div>
                        <WeekdaySelector label='Apply Days' value={data.custom_days || []} onChange={detectTypeFromDays} disabled={processing || view} />
                    </div>

                    <div className='flex-2 space-y-4'>


                        <div className='flex gap-2 text-sm items-start justify-start bg-muted border p-2 rounded-sm text-yellow-700 dark:text-yellow-500'>
                            <Info className='min-w-4 max-h-4 mt-1 ' />
                            <p>Modifier applies only if attached to room/category, within optional start/end dates, and matches day type. </p>
                        </div>

                        <ItemSelector
                            title="Room Categories"
                            items={roomCategories.map(item => ({ id: item.id, title: item.short_name }))}
                            selected={data.categories}
                            onSelected={value => setData('categories', value)}
                            error={errors.categories}
                            disabled={processing || view}
                        />

                        <ItemSelector
                            title="Rooms"
                            items={rooms.map(item => ({ id: item.id, title: item.room_number }))}
                            selected={data.rooms}
                            onSelected={value => setData('rooms', value)}
                            error={errors.categories}
                            disabled={processing || view}
                        />

                    </div>
                </div>

                <DialogFooter>
                    <DialogClose asChild>
                        <Button type='button' variant='outline'>Close</Button>
                    </DialogClose>

                    {!view && <Button type="button" onClick={submit} disabled={processing}>
                        {processing
                            ? <><Spinner /> Saving...</>
                            : <>{edit ? <><Save /> Save</> : 'Create'}</>
                        }
                    </Button>}



                </DialogFooter>

            </DialogContent>
        </Dialog>
    )
}

