import { Head, useForm } from '@inertiajs/react'
import { useEffect } from 'react'
import AppLayout from '@/layouts/app-layout'
import IndexPageLayout from '@/components/core/IndexPageLayout'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Save } from 'lucide-react'
import { BreadcrumbItem } from '@/types'
import AvailabilityRulesList from '@/components/(dashboard)/AvailabilityRules/AvailabilityRulesList'
import InputField, { TextAreaField } from '@/components/core/InputField'
import { Spinner } from '@/components/ui/spinner'
import { Rule } from '@/types/availabilityRules'
import { toast } from 'sonner'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

import MealPackageVariant from './MealPackageVariant'
import ImageSectionCard from '@/components/core/ImageSelectionCard'
import { MealPackageForm } from '@/types/dashboard/meal-package'
import IconOrImageSelector from '@/components/core/IconOrImageSelector'
import { BackendImage } from '@/types/dashboard/image'
import { SystemCurrencyType } from '@/types/dashboard/currency'

const MAX_IMAGES = 4 // For meal package only one image/icon

interface BackendMealPackage extends Omit<MealPackageForm, "images" | 'availabilityRules'> {
    id: number;
    images: BackendImage[];
    availability_rules: Rule[]
}


type MealPackagesPageProps = {
    mealPackage?: BackendMealPackage,
    mode?: 'create' | 'edit' | 'view',
    system_currency: SystemCurrencyType
}


export default function MealPackagePage({ mealPackage, mode = 'create', system_currency }: MealPackagesPageProps) {

    const { data, setData, post, put, processing, errors } = useForm<MealPackageForm>({
        sort_order: mealPackage?.sort_order || 0,
        title: mealPackage?.title || '',
        description: mealPackage?.description || '',
        price: mealPackage?.price || '',
        scope: mealPackage?.scope || 'all_rooms',
        tag: mealPackage?.tag || '',
        is_icon: mealPackage?.is_icon ?? true,
        icon_value: mealPackage?.icon_value ?? '',
        is_allow_select_days: mealPackage?.is_allow_select_days ?? false,
        is_variant: mealPackage?.is_variant ?? true,
        is_published: mealPackage?.is_published ?? true,
        default_availability: mealPackage?.default_availability ?? true,
        images: mealPackage?.images?.map(img => ({
            id: img.id,
            role: img.pivot.role,
            sort_order: img.pivot.sort_order
        })) || [],
        availabilityRules: mealPackage?.availability_rules ?? [],
        variants: mealPackage?.variants || []
    })

    const view = mode === 'view'

    // Create the path on top
    let breadcrumbs: BreadcrumbItem[] = [
        {
            title: 'Meal Packages',
            href: '/dashboard/meal-packages',
        },
        {
            title: 'Create New',
            href: '/dashboard/meal-packages/create',
        },
    ];


    if (mode !== 'create') {
        breadcrumbs.pop()
        breadcrumbs.push({
            title: `#${mealPackage?.id}`,
            href: `/dashboard/meal-packages/${mealPackage?.id}`,
        })
        if (mode === 'edit') {
            breadcrumbs.push({
                title: `edit`,
                href: `/dashboard/meal-packages/${mealPackage?.id}/edit`,
            })
        }
    }


    // Submit the data
    const submit = (e: React.FormEvent) => {
        e.preventDefault()

        if (data.is_variant && data.variants.length <= 1) {
            toast.warning('Please at least two variants are requried')
            return
        }

        if (mode === 'create') {
            post('/dashboard/meal-packages', { onSuccess: () => toast.success('Sucsessfuly Created Meal Package'), onError: (error) => toast.error(error.message || 'Something Worng, Please try again') })
        } else if (mode === 'edit' && mealPackage) {
            put(`/dashboard/meal-packages/${mealPackage.id}`, { onSuccess: () => toast.success('Sucsessfuly Updated the Meal Package'), onError: (error) => toast.error(error.message || 'Something Worng, Please try again') })
        }
    }


    // Load data from backend when editing/viewing
    useEffect(() => {
        if (!mealPackage) return
        setData({
            sort_order: mealPackage.sort_order || 0,
            title: mealPackage.title || '',
            description: mealPackage.description || '',
            price: mealPackage.price || '',
            scope: mealPackage.scope || 'booking',
            tag: mealPackage.tag || '',
            is_icon: mealPackage?.is_icon ?? true,
            icon_value: mealPackage?.icon_value ?? '',
            is_allow_select_days: mealPackage?.is_allow_select_days ?? false,
            is_variant: mealPackage?.is_variant ?? true,
            is_published: mealPackage.is_published ?? true,
            default_availability: mealPackage.default_availability ?? true,
            images: mealPackage.images?.map(img => ({
                id: img.id,
                role: img.pivot.role,
                sort_order: img.pivot.sort_order
            })) || [],
            availabilityRules: mealPackage.availability_rules ?? [],
            variants: mealPackage?.variants || []
        })

    }, [mealPackage])


    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={mode === 'view' ? `Meal Package #${mealPackage?.id}` : mode === 'edit' ? `Edit Meal Package` : "Create Meal Package"} />
            <IndexPageLayout title={'Meal Package'} path='/dashboard/meal-packages' id={mealPackage?.id} mode={mode} description='Manage meal packages for rooms by creating, viewing, and editing options like breakfast, half-board, or full-board. Set prices and availability to let customers easily add meals during room reservations.' >

                <ImageSectionCard uploadFolderType='meals' itemName={mealPackage?.title || 'Meal Package'} data={mealPackage?.images || []} onChange={(value) => setData('images', value)} max={MAX_IMAGES} edit={!view} processing={processing} />

                <div className="flex flex-col lg:flex-row gap-4 mt-6">

                    <div className=" border p-6 rounded-sm bg-card space-y-4 flex-1 h-fit max-w-160">

                        {/* Images */}
                        <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)} disabled={view || processing} />

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

                        {/* Information */}
                        <div className="flex flex-col gap-4">

                            <TextAreaField label='Description' maxLength={100} value={data.description} onChange={(value) => setData('description', value)} placeholder='Write a small description' disabled={view || processing} error={errors.description} />

                            <div className="flex gap-4">
                                <InputField label='Price' type='number' placeholder={data.is_variant ? 'Disabled' : ''} value={data.is_variant ? '' : Number(data.price) || ''} onChange={value => setData('price', value)} startAddon={system_currency} helperMsg={data.is_variant ? "Only can add if don't have any varints" : 'Default price per night per persion'} disabled={view || processing || data.is_variant} error={errors.price} />
                                <div className="space-y-2 flex-1">
                                    <Label>Scope</Label>
                                    <Select value={data.scope} onValueChange={(value: 'booking' | 'room' | 'room_category' | 'all_rooms') => setData("scope", value)} disabled={view || processing} >
                                        <SelectTrigger className='w-full' >
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {/* <SelectItem value="booking">Apply Booking</SelectItem> */}
                                            <SelectItem value="all_rooms">Apply to All Rooms</SelectItem>
                                            <SelectItem value="room_category">Category Specific</SelectItem>
                                            <SelectItem value="room">Room Specific</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>

                            <div className="flex gap-4">
                                <InputField label='Sort Order' type='number' min={0} value={data.sort_order || ''} onChange={value => setData('sort_order', Number(value))} disabled={view || processing} error={errors.sort_order} />
                                <InputField label='Tag' value={data.tag} onChange={value => setData('tag', value)} disabled={view || processing} error={errors.tag} helperMsg='As example "Popular"' />
                            </div>


                            <div className="flex items-center gap-2">
                                <Checkbox checked={data.is_allow_select_days} onCheckedChange={value => setData('is_allow_select_days', Boolean(value))} disabled={view || processing} />
                                <Label>Is Allow Select Days</Label>
                            </div>

                            <div className="flex items-center gap-2">
                                <Checkbox checked={data.is_variant} onCheckedChange={value => setData('is_variant', Boolean(value))} disabled={view || processing} />
                                <Label>Is Variant</Label>
                            </div>
                            <div className="flex items-center gap-2">
                                <Checkbox checked={data.default_availability} onCheckedChange={value => setData('default_availability', Boolean(value))} disabled={view || processing} />
                                <Label>Available by default</Label>
                            </div>
                            <div className="flex items-center gap-2">
                                <Checkbox checked={data.is_published} onCheckedChange={value => setData('is_published', Boolean(value))} disabled={view || processing} />
                                <Label>Published</Label>
                            </div>
                        </div>
                    </div>

                    <div className='w-full  max-w-120 rounded-sm space-y-4'>
                        {
                            mode !== 'create' &&
                            <AvailabilityRulesList card defaultAvailability={data.default_availability} rules={data.availabilityRules} type='MealPackage' id={mealPackage?.id} edit={mode === 'edit'} title={data.title} />
                        }
                        {
                            data.is_variant ? <>
                                <MealPackageVariant view={view} disabled={view || processing} variants={data.variants} setData={setData} defaultAvailability={data.default_availability} system_currency={system_currency} />
                            </> : null
                        }
                    </div>

                </div>
                {!view && <div className='w-full flex justify-start'>
                    <Button type="button" onClick={submit} disabled={processing}>{mode === 'edit' ? <>{processing ? <><Spinner /> Saving...</> : <><Save /> Save Changes</>}</> : <>{processing ? <><Spinner /> Creating...</> : <>Create Meal Package</>}</>}</Button>
                </div>
                }
            </IndexPageLayout>
        </AppLayout >
    )
}
