import InputField, { DateInput, TextAreaField } 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 { Textarea } from '@/components/ui/textarea'
import { Spinner } from '@/components/ui/spinner'
import { useForm } from '@inertiajs/react'
import {
    Ban,
    CirclePlus,
    Clock3,
    Info,
    Lock,
    Save
} from 'lucide-react'
import { Dispatch, SetStateAction, useEffect } from 'react'
import { toast } from 'sonner'

type RoomItem = {
    id: number
    room_number: string
}

type FormProp = {
    room_id: number | null
    start_date: string
    end_date: string
    status: 'blocked' | 'pending' | 'booked'
    source: string
    message: string
}

type AvailabilityItem = {
    id: number
    room_id: number
    start_date: string
    end_date: string
    status: 'blocked' | 'pending' | 'booked'
    source: string
    message?: string
}

type MakerProp = {
    open: boolean
    setOpen: Dispatch<SetStateAction<boolean>>

    availability: AvailabilityItem | null
    setAvailability: Dispatch<SetStateAction<AvailabilityItem | null>>

    rooms: RoomItem[]
    view?: boolean
}

export default function RoomAvailabilityMaker({ open, setOpen, availability, setAvailability, rooms, view = false }: MakerProp) {



    const edit = availability !== null

    const { data, setData, post, put, processing, reset, errors, clearErrors } = useForm<FormProp>({ room_id: null, start_date: '', end_date: '', status: 'blocked', source: 'admin', message: '' })

    const submit = () => {

        console.log('data', `/dashboard/room-availability/${availability?.id}`, data);


        if (edit) {

            put(`/dashboard/room-availability/${availability.id}`, {

                onSuccess: () => {
                    toast.success('Availability updated')
                    handleClose()
                },

                onError: () => {
                    toast.error('Please check the form again')
                }
            })

        } else {

            post('/dashboard/room-availability', {

                onSuccess: () => {
                    toast.success('Availability created')
                    handleClose()
                },

                onError: () => {
                    toast.error('Please check the form again')
                }
            })
        }
    }

    const handleClose = () => {

        setOpen(false)
        setAvailability(null)

        reset()
        clearErrors()
    }

    useEffect(() => {

        console.log('Log', availability);


        if (!availability) return

        setData({
            room_id: availability.room_id,
            start_date: availability.start_date,
            end_date: availability.end_date,
            status: availability.status,
            source: availability.source,
            message: availability.message || ''
        })

    }, [availability])

    useEffect(() => {

        if (!open) {
            handleClose()
        }

    }, [open])

    return (
        <Dialog open={open} onOpenChange={setOpen}>

            <DialogTrigger asChild>
                <Button size='sm' variant='outline'><CirclePlus className="h-4 w-4" />Add Room Availability</Button>
            </DialogTrigger>

            <DialogContent className="min-w-3xl">

                <DialogHeader>

                    <DialogTitle className="flex items-center gap-2">

                        {data.status === 'blocked' && (
                            <Lock className="h-4 w-4 text-red-600" />
                        )}

                        {data.status === 'pending' && (
                            <Clock3 className="h-4 w-4 text-amber-600" />
                        )}

                        {data.status === 'booked' && (
                            <Ban className="h-4 w-4 text-blue-600" />
                        )}

                        {edit
                            ? (view ? `Availability #${availability?.id}` : 'Edit Availability')
                            : 'Create Availability'}

                    </DialogTitle>

                    <DialogDescription>   Manage room blocks, pending reservations, and manual availability overrides.   </DialogDescription>

                </DialogHeader>

                <div className="flex gap-6">

                    {/* LEFT */}
                    <div className="flex-1 space-y-4">

                        {/* ROOM */}
                        <div className="space-y-2">
                            <Label>Room</Label>
                            <Select value={data.room_id?.toString()} onValueChange={(value) => setData('room_id', Number(value))} disabled={processing || view}>
                                <SelectTrigger className="w-full">  <SelectValue placeholder="Select room" />      </SelectTrigger>
                                <SelectContent>
                                    {rooms.map(room => (<SelectItem key={room.id} value={room.id.toString()}> {room.room_number} </SelectItem>))}
                                </SelectContent>
                            </Select>

                            {errors.room_id && <p className="text-sm text-red-600">{errors.room_id}</p>}

                        </div>

                        {/* DATES */}
                        <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>

                        {/* STATUS + SOURCE */}
                        <div className="flex gap-4">

                            <div className="flex-1 space-y-2">
                                <Label>Status</Label>
                                <Select value={data.status} onValueChange={(value: 'blocked' | 'pending' | 'booked') => setData('status', value)} disabled={processing || view}>
                                    <SelectTrigger className="w-full">    <SelectValue />  </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="blocked">Blocked  </SelectItem>
                                        <SelectItem value="pending">Pending  </SelectItem>
                                        <SelectItem value="booked">Booked  </SelectItem>
                                    </SelectContent>
                                </Select>
                                {errors.status && <p className="text-sm text-red-600">{errors.status}</p>}
                            </div>

                            <InputField label='Source' value={data.source} onChange={(value) => setData('source', value)} error={errors.source} disabled={processing || view} placeholder='admin / website / booking.com' className='flex-1' />
                        </div>

                        <TextAreaField label='Message / Reason' value={data.message} onChange={(value) => setData('message', value)} error={errors.message} disabled={processing || view} placeholder='Maintenance block, VIP reservation, external sync note...' className="min-h-28 resize-none" />

                    </div>

                    {/* RIGHT */}
                    <div className="w-80 space-y-4 flex flex-col justify-between">

                        <div className='space-y-4'>
                            {/* INFO */}
                            <div className="rounded-sm border bg-muted/40 p-2">

                                <div className="flex items-start gap-1">

                                    <div className="p-1">
                                        <Info className="h-4 w-4 text-main" />
                                    </div>

                                    <div >

                                        <p className="text-sm font-medium">
                                            Availability Control
                                        </p>

                                        <p className="text-xs text-muted-foreground leading-relaxed">
                                            Blocks and reservations affect room availability across the booking calendar and connected channels like Booking.com.
                                        </p>

                                    </div>

                                </div>

                            </div>

                            {/* STATUS PREVIEW */}
                            <div className="rounded-sm border overflow-hidden">

                                <div className="border-b px-3 py-3 bg-muted/40">
                                    <p className="text-xs uppercase tracking-widest text-muted-foreground">
                                        Preview
                                    </p>
                                </div>

                                <div className="p-3 space-y-4">

                                    <div className={`
                                            rounded-sm border py-2 px-3 transition-all

                                            ${data.status === 'blocked' && 'bg-red-50 border-red-100 dark:bg-red-950/30 dark:border-red-900'}
                                            ${data.status === 'pending' && 'bg-amber-50 border-amber-100 dark:bg-amber-950/30 dark:border-amber-900'}
                                            ${data.status === 'booked' && 'bg-blue-50 border-blue-100 dark:bg-blue-950/30 dark:border-blue-900'}
                                        `}>

                                        <div className="flex items-center justify-between">

                                            <p className="text-sm font-medium capitalize">
                                                {data.status}
                                            </p>

                                            <div className={`
                                            h-2.5 w-2.5 rounded-full
                                            ${data.status === 'blocked' && 'bg-red-500'}
                                            ${data.status === 'pending' && 'bg-amber-500'}
                                            ${data.status === 'booked' && 'bg-blue-500'}
                                        `} />

                                        </div>

                                        <p className="text-xs text-muted-foreground mt-2">
                                            {new Date(data.start_date).toDateString() || '---'} → {new Date(data.end_date).toDateString() || '---'}
                                        </p>

                                    </div>

                                    <div className="space-y-2 text-xs">

                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Source</span>
                                            <span className="font-medium">
                                                {data.source || 'admin'}
                                            </span>
                                        </div>

                                        <div className="flex justify-between">
                                            <span className="text-muted-foreground">Sync Impact</span>
                                            <span className="font-medium">
                                                Calendar + Channels
                                            </span>
                                        </div>

                                    </div>

                                </div>

                            </div>

                        </div>
                        <DialogFooter className='mt-auto'>

                            <DialogClose asChild>

                                <Button type="button" variant="outline">
                                    Close
                                </Button>

                            </DialogClose>

                            {!view && (

                                <Button type="button" onClick={submit} disabled={processing}>
                                    {processing
                                        ? (<>    <Spinner />   Saving... </>)
                                        : (<>   <Save className="h-4 w-4" />    {edit ? 'Save Changes' : 'Create Availability'}</>)}
                                </Button>

                            )}

                        </DialogFooter>
                    </div>

                </div>

            </DialogContent>

        </Dialog >
    )
}