

import IconOrImageSelector from '@/components/core/IconOrImageSelector'
import InputField from '@/components/core/InputField'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
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 { FacilityType } from '@/types/dashboard/facility'
import { useForm } from '@inertiajs/react'
import { CirclePlus, Save } from 'lucide-react'
import { Dispatch, SetStateAction, useEffect } from 'react'
import { toast } from 'sonner'

type FormType = {
    id?: number;
    name: string;
    is_icon: boolean;
    icon_value: string;
    scope: 'room' | 'room_category' | 'all_rooms';
    is_published: boolean
}

type MakerProp = {
    mode?: 'create' | 'edit' | 'view',
    facility: FacilityType | null,
    setFacility: Dispatch<SetStateAction<FacilityType | null>>
    open: boolean,
    setOpen: Dispatch<SetStateAction<boolean>>
}

export default function FacilityMaker({ facility, setFacility, open, setOpen, }: MakerProp) {

    const { data, setData, post, put, processing, reset, errors, clearErrors } = useForm<FormType>({
        name: '',
        is_icon: true,
        icon_value: 'string',
        scope: 'all_rooms',
        is_published: true
    })

    const edit = facility !== null

    const submit = () => {
        if (edit) {
            put(`/dashboard/facilities/${facility.id}`, { onSuccess: () => { toast.success('Sucsessfuly Updated the Facility'); handleClose() }, onError: (error) => toast.error(error.message || 'Please check again!') })
        } else {
            post('/dashboard/facilities', { onSuccess: () => { toast.success('Sucsessfuly Created a Facility'); handleClose() }, onError: (error) => toast.error(error.message || 'Please check again!') })
        }
    }


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


    useEffect(() => {
        if (!facility) return
        setData({
            name: facility.name,
            is_icon: facility.is_icon,
            icon_value: facility.icon_value,
            scope: facility.scope,
            is_published: facility.is_published
        })
    }, [facility])

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



    return <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild>
            <Button variant='outline' ><CirclePlus />Add New</Button>
        </DialogTrigger>
        <DialogContent>
            <DialogHeader>
                <DialogTitle>{edit ? 'Edit the ' : 'Create New '}Facility</DialogTitle>
                <DialogDescription>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate sequi quam.</DialogDescription>
            </DialogHeader>

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

                    <IconOrImageSelector value={data.icon_value} is_icon={data.is_icon} onChangeType={value => setData('is_icon', value)} onChangeValue={value => setData('icon_value', value)} />

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


                </div>
                <div className='flex gap-4 items-center'>
                    <div className="space-y-2 flex-1">
                        <Label>Scope</Label>
                        <Select value={data.scope} onValueChange={(value: 'room' | 'room_category' | 'all_rooms') => setData("scope", value)} disabled={processing} >
                            <SelectTrigger className='w-full' >
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all_rooms">Apply All</SelectItem>
                                <SelectItem value="room_category">Category Specific</SelectItem>
                                <SelectItem value="room">Room Specific</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>

                    <div className="flex-1 flex items-center gap-2">
                        <Checkbox checked={data.is_published} onCheckedChange={value => setData('is_published', Boolean(value))} disabled={processing} />
                        <Label>Published</Label>
                    </div>
                </div>

            </div>
            <DialogFooter >
                <DialogClose asChild><Button type='button' variant='outline'>Close</Button></DialogClose>
                <Button type="button" onClick={submit} disabled={processing}> {processing ? <><Spinner /> {edit ? 'Saving' : 'Creating'}...</> : <>{edit ? <><Save /> Save</> : 'Create'}</>} </Button>
            </DialogFooter>

        </DialogContent>
    </Dialog>
}
