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 Modal from "@admin/ui/Modal";
import Row from "@admin/ui/Row";
import Col from "@admin/ui/Col";
import { useEffect, useState } from "react";
import { useFormResponse } from '@/hooks/useFormResponse';
import { useForm } from "@inertiajs/react";

export default function EditEventRoom({ isOpen, onClose, initialData }){
    const {data, setData, put, processing, errors} = useForm({
        'name': '',
        'primary_photo': '',
        'price_fbu': '',
        'price_usd': '',
        'price_eur': '',
        'short_description': '',
        'full_description': '',
        'capacity': '',
        'layouts': [],
        'equipment': [],
        'gallery': [],
        'status': true,
    });

    const [presetPreviews, setPresetPreviews] = useState([]);
    // Store raw text for layouts and equipment to allow typing commas
    const [layoutsText, setLayoutsText] = useState('');
    const [equipmentText, setEquipmentText] = useState('');

    useEffect(() => {
        if (initialData) {
          // Handle gallery - ensure it's an array
          let gallery = [];
          if (initialData?.gallery) {
              if (Array.isArray(initialData.gallery)) {
                  gallery = initialData.gallery;
              } else if (typeof initialData.gallery === 'string') {
                  // If it's a JSON string, parse it
                  try {
                      const parsed = JSON.parse(initialData.gallery);
                      gallery = Array.isArray(parsed) ? parsed : [];
                  } catch (e) {
                      gallery = [];
                  }
              }
          }
          
          // Filter out empty/null values
          const validGallery = gallery.filter(item => item && typeof item === 'string' && item.trim() !== '');
          
          const layouts = initialData?.layouts || [];
          const equipment = initialData?.equipment || [];
          setData({
              name: initialData?.name || '',
              primary_photo: initialData?.primary_photo || '',
              price_fbu: initialData?.price_fbu || '',
              price_usd: initialData?.price_usd || '',
              price_eur: initialData?.price_eur || '',
              short_description: initialData?.short_description || '',
              full_description: initialData?.full_description || '',
              capacity: initialData?.capacity || '',
              layouts: layouts,
              equipment: equipment,
              gallery: validGallery,
              status: initialData?.status === 1 || initialData?.status === true,
          });

          // Set layouts and equipment text for display
          setLayoutsText(Array.isArray(layouts) ? layouts.join(', ') : '');
          setEquipmentText(Array.isArray(equipment) ? equipment.join(', ') : '');

          // Set preset previews for gallery images
          if (validGallery.length > 0) {
              setPresetPreviews(validGallery.map(filename => `/storage/${filename}`));
          } else {
              setPresetPreviews([]);
          }
        } else {
            // Reset when modal closes
            setPresetPreviews([]);
        }
    }, [initialData, setData]);

    const handlePrimaryPhotoSuccess = (filename) => {
        console.log('Primary photo uploaded:', filename);
        setData('primary_photo', filename);
    };

    const handleGallerySuccess = ({ filenames }) => {
        // Ensure filenames is an array
        const validFilenames = Array.isArray(filenames) ? filenames.filter(f => f && f.trim() !== '') : [];
        // Update the gallery data
        setData('gallery', validFilenames);
        // Update preset previews to match the gallery
        setPresetPreviews(validFilenames.map(filename => `/storage/${filename}`));
    };

    const handleError = (error) => {
        console.error("Upload error:", error);
    };

    const handleLayoutsChange = (e) => {
        const value = e.target.value;
        // Store raw text to allow typing commas
        setLayoutsText(value);
        // Convert to array for data storage
        const layoutsArray = value.split(',')
            .map(item => item.trim())
            .filter(item => item.length > 0);
        setData('layouts', layoutsArray);
    };

    const handleLayoutsBlur = () => {
        // On blur, ensure the text matches the array
        setLayoutsText(data.layouts.join(', '));
    };

    const handleEquipmentChange = (e) => {
        const value = e.target.value;
        // Store raw text to allow typing commas
        setEquipmentText(value);
        // Convert to array for data storage
        const equipmentArray = value.split(',')
            .map(item => item.trim())
            .filter(item => item.length > 0);
        setData('equipment', equipmentArray);
    };

    const handleEquipmentBlur = () => {
        // On blur, ensure the text matches the array
        setEquipmentText(data.equipment.join(', '));
    };

    const handleSave = (event) => {
        event.preventDefault();
        const formResponse = useFormResponse(() => {
            onClose?.(); 
        });
    
        put(`/admin/api/update_event_room/${initialData.id}`, {
            preserveScroll: true,
            onSuccess: formResponse.onSuccess, 
            onError: formResponse.onError, 
        });
    };    

    return(
    <>
    <Modal isOpen={isOpen} onClose={onClose} title={`Edit ${initialData?.name || 'Event Room'}`} size="large"
    primaryButtonText="Save Changes"
    onPrimaryAction={handleSave}
    processing={processing}
    >
        <form onSubmit={handleSave}>
            <Row>
                <Col md="6">
                    <FormGroup
                        id="name"
                        label="Room Name"
                        type="text"
                        value={data.name}
                        onChange={(e) => setData("name", e.target.value)}
                        required
                        invalidFeedback={errors.name}
                    />

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

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

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

                    <FormGroup
                        id="capacity"
                        label="Capacity"
                        type="number"
                        value={data.capacity}
                        onChange={(e) => setData("capacity", e.target.value)}
                        helpText="Maximum number of people"
                        invalidFeedback={errors.capacity}
                        min="1"
                    />

                    <FormGroup
                        id="layouts"
                        label="Layouts"
                        as="textarea"
                        value={layoutsText}
                        helpText="Enter layouts separated by commas"
                        onChange={handleLayoutsChange}
                        onBlur={handleLayoutsBlur}
                        rows="3"
                        invalidFeedback={errors.layouts}
                    />
                    {data.layouts.length > 0 && (
                        <div className="mb-2">
                            <small className="text-muted">Current layouts: </small>
                            {data.layouts.map((layout, index) => (
                                <span key={index} className="badge badge-secondary mr-1">{layout}</span>
                            ))}
                        </div>
                    )}

                    <FormGroup
                        id="equipment"
                        label="Equipment"
                        as="textarea"
                        value={equipmentText}
                        helpText="Enter equipment separated by commas"
                        onChange={handleEquipmentChange}
                        onBlur={handleEquipmentBlur}
                        rows="3"
                        invalidFeedback={errors.equipment}
                    />
                    {data.equipment.length > 0 && (
                        <div className="mb-2">
                            <small className="text-muted">Current equipment: </small>
                            {data.equipment.map((item, index) => (
                                <span key={index} className="badge badge-secondary mr-1">{item}</span>
                            ))}
                        </div>
                    )}
                </Col>
                <Col md="6">
                    <FormGroup
                        id="short_description"
                        label="Short Description"
                        as="textarea"
                        value={data.short_description}
                        helpText="Provide a brief description (minimum 20 characters)"
                        onChange={(e) => setData("short_description", e.target.value)}
                        rows="4"
                        invalidFeedback={errors.short_description}
                    />

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

            <Row>
                <Col md="6">
                    <FileUploadInput 
                        label="Upload Primary Photo (800x571)px" 
                        buttonText={"Choose file (800x571)"}
                        uploadUrl="/admin/api/event_room/upload_image"
                        onSuccess={handlePrimaryPhotoSuccess}
                        onError={handleError}
                        previewUrl={data.primary_photo ? `/storage/${data.primary_photo}` : ''}
                        invalidFeedback={errors.primary_photo}
                    />
                </Col>
                <Col md="6">
                    <label className="label">Gallery Photos (1123x700)px</label>
                    <MultiImageUploadInput
                        label="Upload Gallery Images (1123x700)px"
                        inputId="galleryUploadEdit"
                        buttonText="Choose gallery images (1123x700)"
                        uploadUrl="/admin/api/event_room/upload_multiple"
                        onSuccess={handleGallerySuccess}
                        onError={handleError}
                        presetPreviews={presetPreviews}
                    />
                    <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 }))
                }                  
            />
        </form>
    </Modal>
    </>);
}

