import FeatureSelector from "@/components/core/FeatureSelector";
import IndexPageLayout from "@/components/core/IndexPageLayout";
import InputField, { TextAreaField } from "@/components/core/InputField";
import RichTextEditor from "@/components/core/RichTextEditor/RichTextEditor";
import SwitchField from "@/components/core/SwitchField";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import AppLayout from "@/layouts/app-layout";
import { BreadcrumbItem } from "@/types";
import { AddOnType } from "@/types/dashboard/add-ons";
import { SystemCurrencyType } from "@/types/dashboard/currency";
import { FacilityType } from "@/types/dashboard/facility";
import { MealPackageType } from "@/types/dashboard/meal-package";
import { RoomCategoriesRef } from "@/types/room";
import { Head, useForm } from "@inertiajs/react"
import { Save } from "lucide-react";
import { useEffect } from "react";
import { toast } from "sonner";


type RoomCategoriesTypes = {
    category: RoomCategoriesRef,
    mode?: 'create' | 'edit' | 'view',
    facilities: FacilityType[],
    facilities_data?: number[],
    meal_packages: MealPackageType[],
    meal_packages_data?: number[],
    add_ons: AddOnType[],
    add_ons_data?: number[],
    system_currency: SystemCurrencyType
}

type FormType = {
    id?: number;
    short_name: string;
    name: string;
    slug: string;
    description: string;
    details: string | null;
    policies: string | null;

    sort_order: number;

    base_price: number;

    max_adults: number;
    max_children: number;
    default_bed_count: number;
    default_bathroom_count: number;
    default_size: number;

    is_published: boolean;

    facilities: number[];
    meal_packages: number[];
    add_ons: number[];
}


export default function Category({ category, mode = 'create', facilities, facilities_data, meal_packages, meal_packages_data, add_ons, add_ons_data, system_currency }: RoomCategoriesTypes) {

    const view = mode === 'view'

    const { data, setData, post, put, processing, errors } = useForm<FormType>({
        short_name: category?.short_name || '',
        name: category?.name || '',
        slug: category?.slug || '',
        description: category?.description || '',
        sort_order: category?.sort_order,

        base_price: category?.base_price,

        details: category?.details || '',
        policies: category?.policies || '',

        max_adults: category?.max_adults,
        max_children: category?.max_children,
        default_bed_count: category?.default_bed_count,
        default_bathroom_count: category?.default_bathroom_count,
        default_size: category?.default_size,

        is_published: category?.is_published ?? false,

        facilities: facilities_data || [],
        meal_packages: meal_packages_data || [],
        add_ons: add_ons_data || []
    })

    const submit = () => {

        if (mode === 'create') {
            post('/dashboard/room-categories', {
                onSuccess: (e) => { toast.success('Sucsessfuly Created the Room Cateogry') },
                onError: (error) => { toast.error(error.message || 'Something went worgn. Please try again!'); }
            }) // create new
        } else if (mode === 'edit' && category) {
            put(`/dashboard/room-categories/${category.id}`, {
                onSuccess: (e) => { toast.success('Sucsessfuly Updated the Room Cateogrye') },
                onError: (error) => { toast.error(error.message || 'Something went worgn. Please try again!'); }
            }) // update existing
        }
    }

    const breadcrumbs: BreadcrumbItem[] = [
        {
            title: 'Room Category',
            href: '/dashboard/room-categories',
        },
        {
            title: mode === 'edit' ? `Edit Room Category` : "Create Room Category",
            href: '#',
        },
    ];


    useEffect(() => {
        setData({
            ...category,
            facilities: facilities_data || [],
            meal_packages: meal_packages_data || [],
            add_ons: add_ons_data || []
        })
    }, [category, facilities_data, meal_packages_data, add_ons_data])


    return (
        <AppLayout breadcrumbs={breadcrumbs} >
            <Head title={mode === 'view' ? `Room Category #${category?.id}` : mode === 'edit' ? `Edit Room Category #${category?.id}` : "Create New Room Category"} />

            <IndexPageLayout title='Room Category' description="Add a new room category to organize your rooms, like Deluxe, Standard, Suite, or Family." path='/dashboard/room-categories' id={category?.id} mode={mode} >
                <div className="flex gap-6 w-full">
                    <div className=" flex-1 bg-card border rounded-sm p-4  space-y-4 h-fit">
                        <InputField label='Name' type='text' value={data.name || ''} onChange={value => setData('name', value)} disabled={view || processing} error={errors.name} />

                        <div className="flex gap-4">
                            <InputField label='Short Name' type='text' value={data.short_name || ''} onChange={value => setData('short_name', value)} disabled={view || processing} error={errors.short_name} />
                            <InputField label='Slug (Url)' type='text' value={data.slug || ''} onChange={value => setData('slug', value)} disabled={view || processing} error={errors.slug} />
                        </div>

                        <div className="flex gap-4">
                            <InputField label='Sort Order' type='number' value={data.sort_order || ''} onChange={value => setData('sort_order', Number(value))} disabled={view || processing} error={errors.sort_order} />
                            <InputField label='Price' startAddon={system_currency} type='number' value={Number(data.base_price) || ''} onChange={value => setData('base_price', Number(value))} disabled={view || processing} error={errors.base_price} />
                        </div>

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


                        <div className="flex gap-4">
                            <InputField label='Max Adults' type='number' value={data.max_adults || ''} onChange={value => setData('max_adults', Number(value))} disabled={view || processing} error={errors.max_adults} />
                            <InputField label='Max Children' type='number' value={data.max_children || ''} onChange={value => setData('max_children', Number(value))} disabled={view || processing} error={errors.max_children} />
                        </div>

                        <div className="flex gap-4">
                            <InputField label='Bed Count' type='number' value={data.default_bed_count || ''} onChange={value => setData('default_bed_count', Number(value))} disabled={view || processing} error={errors.default_bed_count} />
                            <InputField label='Bathrooms' type='number' value={data.default_bathroom_count || ''} onChange={value => setData('default_bathroom_count', Number(value))} disabled={view || processing} error={errors.max_adults} />
                            <InputField label='Room Area (m²)' type='number' value={data.default_size || ''} onChange={value => setData('default_size', Number(value))} disabled={view || processing} error={errors.default_size} />
                        </div>

                        <SwitchField title='Published' checked={data.is_published} onChecked={(value: boolean) => setData('is_published', value)} disabled={view || processing} description='If turned off, the room will not be shown to guests.' />

                    </div>

                    <div className="space-y-10 bg-card p-4 rounded-sm border flex-1 h-fit">
                        <FeatureSelector
                            title="Facilities"
                            items={facilities}
                            selected={data.facilities}
                            onSelected={value => setData('facilities', value)}
                            edit={mode !== 'view'}
                            disabled={processing}
                            system_currency={system_currency}
                        />

                        <FeatureSelector
                            title="Meal Packages"
                            items={meal_packages}
                            selected={data.meal_packages}
                            onSelected={value => setData('meal_packages', value)}
                            edit={mode !== 'view'}
                            disabled={processing}
                            card
                            system_currency={system_currency}
                        />

                        {/* <FeatureSelector
                            title="Add-Ons"
                            items={add_ons}
                            selected={data.add_ons}
                            onSelected={value => setData('add_ons', value)}
                            edit={mode !== 'view'}
                            disabled={processing}
                            card
                        /> */}

                    </div>
                </div>

                <RichTextEditor label="Detailed Description" error={errors.details} value={data.details} onChange={value => setData('details', value)} />
                <RichTextEditor label="Room Policies" error={errors.policies} value={data.policies} onChange={value => setData('policies', value)} />

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

            </IndexPageLayout>
        </AppLayout >

    )
}
