import Card from "@admin/ui/Card";
import Col from "@admin/ui/Col";
import FormGroup from "@admin/ui/forms/FormGroup";
import Switch from "@admin/ui/forms/Switch";
import FileUploadInput from "@admin/ui/forms/FileUploadInput";
import MultiImageUploadInput from "@admin/ui/forms/MultiImageUploadInput";
import Row from "@admin/ui/Row";
import { useForm } from "@inertiajs/react";
import { useFormResponse } from '@/hooks/useFormResponse';
import { Toaster } from "react-hot-toast";
import { useState } from "react";

export default function Accommodation(){
    const {data, setData, post, processing, errors, reset} = useForm({
        'room_name': '',
        'room_category': '',
        'primary_photo': '',
        'price_fbu': '',
        'price_usd': '',
        'price_eur': '',
        'description': '',
        'full_description': '',
        'size': '',
        'bed_type': '',
        'view': '',
        'amenities': [],
        'gallery': [],
        'status': true,
        'featured': false,
    });

    // Store raw text for amenities to allow typing commas
    const [amenitiesText, setAmenitiesText] = useState('');

    const handlePrimaryPhotoSuccess = (filename) => {
        if (filename) {
            setData('primary_photo', filename);
        }
    };

    const handleGallerySuccess = (response) => {
        const filenames = response?.filenames || (Array.isArray(response) ? response : []);
        if (Array.isArray(filenames)) {
            setData('gallery', filenames);
        }
    };

    const handleError = (error) => {
        toast.error('Failed to upload image');
    };

    const handleAmenitiesChange = (e) => {
        const value = e.target.value;
        setAmenitiesText(value);
        const amenitiesArray = value.split(',')
            .map(item => item.trim())
            .filter(item => item.length > 0);
        setData('amenities', amenitiesArray);
    };

    const handleAmenitiesBlur = () => {
        setAmenitiesText(data.amenities?.join(', ') || '');
    };

    const handleSubmit = (event) => {
        event.preventDefault();
        const formResponse = useFormResponse(reset);
        post('/admin/accommodations/store', {
            ...formResponse,
            preserveScroll: true,
        });
    }

    return(
        <>
        <Toaster />
        <Row md="12">
            <Col lg="12">
            <h2 className="page-title">Create New Accommodation</h2>
            <p className="text-muted">Add room types and accommodation details</p>
            <Row>
            <Col lg="12">
            <Card md="12" title="Accommodation Details">
            <form onSubmit={handleSubmit}>
                <Row>
                    <Col md="6">
                        <FormGroup
                            id="room_category"
                            label="Room Category"
                            type="text"
                            value={data.room_category}
                            onChange={(e) => {
                                setData("room_category", e.target.value);
                                // Auto-populate room_name from category if room_name is empty
                                if (!data.room_name || data.room_name === data.room_category) {
                                    setData("room_name", e.target.value);
                                }
                            }}
                            required
                            invalidFeedback={errors.room_category}
                            helpText="Enter the room category (e.g., Simple, Standard, Silver, Golden, VIP). This will also be used as the room name."
                        />

                        <FormGroup 
                            label="Price (BIF)" 
                            type="number"
                            value={data.price_fbu}
                            onChange={(e) => setData('price_fbu', e.target.value)}
                            helpText="Enter price in Burundian Franc"
                            invalidFeedback={errors.price_fbu}
                            min="0.01"
                            step="0.01"
                            required
                        />

                        <FormGroup 
                            label="Price (USD)" 
                            type="number"
                            value={data.price_usd}
                            onChange={(e) => setData('price_usd', e.target.value)}
                            helpText="Enter price in US Dollars"
                            invalidFeedback={errors.price_usd}
                            min="0.01"
                            step="0.01"
                            required
                        />

                        <FormGroup 
                            label="Price (EUR)" 
                            type="number"
                            value={data.price_eur}
                            onChange={(e) => setData('price_eur', e.target.value)}
                            helpText="Enter price in Euros"
                            invalidFeedback={errors.price_eur}
                            min="0.01"
                            step="0.01"
                        />

                        <FormGroup
                            id="size"
                            label="Room Size"
                            type="text"
                            value={data.size}
                            onChange={(e) => setData("size", e.target.value)}
                            helpText="e.g., 25 sqm"
                            invalidFeedback={errors.size}
                        />

                        <FormGroup
                            id="bed_type"
                            label="Bed Type"
                            type="text"
                            value={data.bed_type}
                            onChange={(e) => setData("bed_type", e.target.value)}
                            helpText="e.g., King Bed, Twin Beds"
                            invalidFeedback={errors.bed_type}
                        />

                        <FormGroup
                            id="view"
                            label="View"
                            type="text"
                            value={data.view}
                            onChange={(e) => setData("view", e.target.value)}
                            helpText="e.g., Ocean View, Garden View"
                            invalidFeedback={errors.view}
                        />
                    </Col>
                    <Col md="6">
                        <FormGroup
                            id="description"
                            label="Brief Description"
                            as="textarea"
                            value={data.description}
                            helpText="Provide a brief description (minimum 20 characters)"
                            onChange={(e) => setData("description", e.target.value)}
                            rows="4"
                            invalidFeedback={errors.description}
                            required
                        />

                        <FormGroup
                            id="full_description"
                            label="Full Description"
                            as="textarea"
                            value={data.full_description}
                            helpText="Detailed description for the room (size, bed type, view, etc.)"
                            onChange={(e) => setData("full_description", e.target.value)}
                            rows="5"
                            invalidFeedback={errors.full_description}
                        />

                        <FormGroup
                            id="amenities"
                            label="Amenities"
                            as="textarea"
                            value={amenitiesText}
                            helpText="Enter amenities separated by commas (e.g., WiFi, TV, Desk, Balcony, Coffee/Tea maker)"
                            onChange={handleAmenitiesChange}
                            onBlur={handleAmenitiesBlur}
                            rows="3"
                            invalidFeedback={errors.amenities}
                        />
                        {data.amenities.length > 0 && (
                            <div className="mb-2">
                                <small className="text-muted">Current amenities: </small>
                                {data.amenities.map((amenity, index) => (
                                    <span key={index} className="badge badge-secondary mr-1">{amenity}</span>
                                ))}
                            </div>
                        )}
                    </Col>
                </Row>

                <Row>
                    <Col md="6">
                        <FileUploadInput 
                            label="Upload Primary Photo (800x571)px" 
                            buttonText={"Choose file (800x571)"}
                            uploadUrl="/admin/api/accommodation/upload_image"
                            onSuccess={handlePrimaryPhotoSuccess}
                            onError={handleError}
                            invalidFeedback={errors.primary_photo}
                        />
                        {data.primary_photo && (
                            <img 
                                src={`/storage/${data.primary_photo}`} 
                                alt="Primary photo preview" 
                                className="img-thumbnail mt-2"
                                style={{ maxWidth: '300px', maxHeight: '200px' }}
                            />
                        )}
                    </Col>
                    <Col md="6">
                        <label className="label">Gallery Photos (1123x700)px</label>
                        <MultiImageUploadInput
                            label="Upload Gallery Images (1123x700)px"
                            inputId="galleryUpload"
                            buttonText="Choose gallery images (1123x700)"
                            uploadUrl="/admin/api/accommodation/upload_multiple"
                            onSuccess={handleGallerySuccess}
                            onError={handleError}
                            presetPreviews={data.gallery.map(img => `/storage/${img}`)}
                        />
                        <small className="text-muted d-block mt-1">Recommended size: 1123x700 pixels</small>
                        {errors.gallery && (
                            <div className="invalid-feedback d-block">{errors.gallery}</div>
                        )}
                    </Col>
                </Row>

                <Switch
                    id="statusSwitch"
                    label="Active"
                    checked={data.status}
                    onChange={({ target: { checked } }) =>
                        setData(prevData => ({ ...prevData, status: checked }))
                    }                  
                />
                <Switch
                    id="featuredSwitch"
                    label="Featured"
                    checked={data.featured}
                    onChange={({ target: { checked } }) =>
                        setData(prevData => ({ ...prevData, featured: checked }))
                    }                  
                />
                <br/>
                <button type="submit" className="btn btn-primary" disabled={processing}>
                    Save Accommodation
                </button>
            </form>
            </Card>
            </Col>
            </Row>
            </Col>
        </Row>
        </>
    );
}

