import React, { useState, useEffect } from 'react';
import AdminLayout from '@/Layouts/AdminLayout';
import { Head, useForm, Link } from '@inertiajs/react';
import PrimaryButton from '@/Components/PrimaryButton';
import InputLabel from '@/Components/InputLabel';
import TextInput from '@/Components/TextInput';
import InputError from '@/Components/InputError';
import { 
    ArrowLeftIcon, 
    PhotoIcon, 
    XMarkIcon,
    CalendarIcon,
    ClockIcon,
    MapPinIcon,
    CurrencyDollarIcon,
    TicketIcon,
    PencilSquareIcon // Changed to reflect the "Edit" context
} from '@heroicons/react/24/outline';

// --- Reusable Component: FormSection (for clear grouping) ---
const FormSection = ({ title, description, children }) => (
    <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 lg:gap-8 border-t border-gray-200 pt-8">
        <div className="lg:col-span-1">
            <h3 className="text-xl font-bold text-gray-800 flex items-center">
                <PencilSquareIcon className="w-6 h-6 mr-2 text-emerald-500" />
                {title}
            </h3>
            <p className="mt-2 text-sm text-gray-500">{description}</p>
        </div>
        <div className="lg:col-span-2 space-y-6">
            {children}
        </div>
    </div>
);


export default function Edit({ event, auth }) {
    const [imagePreviews, setImagePreviews] = useState([]);
    const [existingImages, setExistingImages] = useState(event.images_url || []);

    const { data, setData, post, processing, errors } = useForm({
        title: event.title || '',
        description: event.description || '',
        date: event.date || '',
        time: event.time || '',
        location: event.location || '',
        type: event.type || 'free',
        price: event.price || '',
        images: [],
        existing_images: event.images || [],
        _method: 'put',
    });

    useEffect(() => {
        // Ensure data sync on component mount/event change
        setExistingImages(event.images_url || []);
        setData('existing_images', event.images || []);
    }, [event]);

    const handleImageChange = (e) => {
        const files = Array.from(e.target.files);
        setData('images', [...data.images, ...files]);

        files.forEach(file => {
            const reader = new FileReader();
            reader.onload = (e) => {
                setImagePreviews(prev => [...prev, e.target.result]);
            };
            reader.readAsDataURL(file);
        });
    };

    const handleRemoveNewImage = (index) => {
        const newImages = data.images.filter((_, i) => i !== index);
        const newImagePreviews = imagePreviews.filter((_, i) => i !== index);
        setData('images', newImages);
        setImagePreviews(newImagePreviews);
    };

    const handleRemoveExistingImage = (index) => {
        const newExistingImages = existingImages.filter((_, i) => i !== index);
        const newExistingImagePaths = data.existing_images.filter((_, i) => i !== index);
        setExistingImages(newExistingImages);
        setData('existing_images', newExistingImagePaths);
    };

    const submit = (e) => {
        e.preventDefault();
        post(route('admin.events.update', event.id), {
            forceFormData: true,
            // Added simple toast/notification on success/error (Inertia pattern)
            onSuccess: () => alert('Event successfully updated!'), 
            onError: () => alert('There was an error updating the event.'),
        });
    };

    return (
        <AdminLayout user={auth.user}>
            <Head title={`Edit: ${event.title}`} />

            <div className="py-8"> {/* Increased spacing */}
                <div className="max-w-6xl mx-auto sm:px-6 lg:px-8"> {/* Wider container */}
                    
                    {/* --- Page Header --- */}
                    <div className="mb-6 flex flex-col md:flex-row md:items-center md:justify-between">
                        <div className="flex-1 min-w-0">
                            <Link 
                                href={route('admin.events.index')} 
                                className="inline-flex items-center text-sm font-medium text-gray-500 hover:text-emerald-600 transition duration-150"
                            >
                                <ArrowLeftIcon className="-ml-0.5 mr-1 h-5 w-5" aria-hidden="true" />
                                Back to Events List
                            </Link>
                            <h1 className="mt-2 text-3xl font-extrabold leading-7 text-gray-900 sm:text-4xl sm:truncate">
                                Editing: **{event.title}**
                            </h1>
                        </div>
                    </div>

                    {/* --- Main Form Card --- */}
                    <div className="bg-white shadow-2xl sm:rounded-xl overflow-hidden border border-gray-100">
                        <form onSubmit={submit} className="p-6 sm:p-10 space-y-10">
                            
                            {/* Section 1: Event Details */}
                            <FormSection 
                                title="Basic Event Information"
                                description="Set the main title and provide a detailed, engaging description for your attendees."
                            >
                                <div>
                                    <InputLabel htmlFor="title" value="Event Title" />
                                    <TextInput
                                        id="title"
                                        type="text"
                                        value={data.title}
                                        className="mt-1 block w-full rounded-lg border-gray-300 focus:border-emerald-500 focus:ring-emerald-500 shadow-sm"
                                        onChange={(e) => setData('title', e.target.value)}
                                        required
                                        autoFocus
                                    />
                                    <InputError message={errors.title} className="mt-2" />
                                </div>
                                <div>
                                    <InputLabel htmlFor="description" value="Description" />
                                    <textarea
                                        id="description"
                                        value={data.description}
                                        rows="6" // Increased rows for better editing experience
                                        className="mt-1 block w-full border-gray-300 focus:border-emerald-500 focus:ring-emerald-500 rounded-lg shadow-sm"
                                        onChange={(e) => setData('description', e.target.value)}
                                    ></textarea>
                                    <InputError message={errors.description} className="mt-2" />
                                </div>
                            </FormSection>

                            {/* Section 2: Date, Time & Location */}
                            <FormSection 
                                title="Scheduling & Venue"
                                description="Specify the exact date, time, and physical (or virtual) location of the event."
                            >
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                                    {/* Date Field */}
                                    <div>
                                        <InputLabel htmlFor="date" value="Date" />
                                        <div className="mt-1 relative rounded-lg shadow-sm">
                                            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                                <CalendarIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
                                            </div>
                                            <TextInput
                                                id="date"
                                                type="date"
                                                value={data.date}
                                                className="mt-1 block w-full pl-10 rounded-lg border-gray-300 focus:border-emerald-500 focus:ring-emerald-500"
                                                onChange={(e) => setData('date', e.target.value)}
                                                required
                                            />
                                        </div>
                                        <InputError message={errors.date} className="mt-2" />
                                    </div>
                                    
                                    {/* Time Field */}
                                    <div>
                                        <InputLabel htmlFor="time" value="Time" />
                                        <div className="mt-1 relative rounded-lg shadow-sm">
                                            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                                <ClockIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
                                            </div>
                                            <TextInput
                                                id="time"
                                                type="time"
                                                value={data.time}
                                                className="mt-1 block w-full pl-10 rounded-lg border-gray-300 focus:border-emerald-500 focus:ring-emerald-500"
                                                onChange={(e) => setData('time', e.target.value)}
                                            />
                                        </div>
                                        <InputError message={errors.time} className="mt-2" />
                                    </div>
                                </div>
                                
                                {/* Location Field */}
                                <div>
                                    <InputLabel htmlFor="location" value="Location / Venue Name" />
                                    <div className="mt-1 relative rounded-lg shadow-sm">
                                        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                            <MapPinIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
                                        </div>
                                        <TextInput
                                            id="location"
                                            type="text"
                                            value={data.location}
                                            placeholder="e.g., Grand Convention Center, Online Zoom Link, etc."
                                            className="mt-1 block w-full pl-10 rounded-lg border-gray-300 focus:border-emerald-500 focus:ring-emerald-500"
                                            onChange={(e) => setData('location', e.target.value)}
                                        />
                                    </div>
                                    <InputError message={errors.location} className="mt-2" />
                                </div>
                            </FormSection>

                            {/* Section 3: Pricing */}
                            <FormSection 
                                title="Ticketing & Price"
                                description="Select the event type (Free or Paid) and set the ticket price if applicable."
                            >
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                                    {/* Event Type Select */}
                                    <div>
                                        <InputLabel htmlFor="type" value="Event Type" />
                                        <div className="mt-1 relative rounded-lg shadow-sm">
                                            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                                <TicketIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
                                            </div>
                                            <select
                                                id="type"
                                                value={data.type}
                                                className="mt-1 block w-full pl-10 border-gray-300 focus:border-emerald-500 focus:ring-emerald-500 rounded-lg shadow-sm"
                                                onChange={(e) => setData('type', e.target.value)}
                                            >
                                                <option value="free">Free Event</option>
                                                <option value="paid">Paid Ticket</option>
                                            </select>
                                        </div>
                                        <InputError message={errors.type} className="mt-2" />
                                    </div>
                                    
                                    {/* Price Field (Conditional) */}
                                    {data.type === 'paid' && (
                                        <div>
                                            <InputLabel htmlFor="price" value="Price (USD)" />
                                            <div className="mt-1 relative rounded-lg shadow-sm">
                                                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                                    <CurrencyDollarIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
                                                </div>
                                                <TextInput
                                                    id="price"
                                                    type="number"
                                                    value={data.price}
                                                    placeholder="0.00"
                                                    className="mt-1 block w-full pl-10 rounded-lg border-gray-300 focus:border-emerald-500 focus:ring-emerald-500"
                                                    onChange={(e) => setData('price', e.target.value)}
                                                    step="0.01"
                                                />
                                            </div>
                                            <InputError message={errors.price} className="mt-2" />
                                        </div>
                                    )}
                                </div>
                            </FormSection>

                            {/* Section 4: Event Images */}
                            <FormSection 
                                title="Event Media"
                                description="Upload images to showcase your event. You can remove existing images or add new ones below."
                            >
                                {/* Drag & Drop Area */}
                                <div className="mt-2 flex justify-center px-6 pt-5 pb-6 border-2 border-emerald-300 border-dashed rounded-lg hover:border-emerald-400 transition-colors bg-emerald-50/50">
                                    <div className="space-y-1 text-center">
                                        <PhotoIcon className="mx-auto h-12 w-12 text-emerald-500" />
                                        <div className="flex text-sm text-gray-600">
                                            <label
                                                htmlFor="images"
                                                className="relative cursor-pointer bg-white rounded-md font-medium text-emerald-600 hover:text-emerald-700 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-emerald-500"
                                            >
                                                <span>Upload files</span>
                                                <input id="images" name="images[]" type="file" multiple className="sr-only" onChange={handleImageChange} />
                                            </label>
                                            <p className="pl-1 text-gray-500">or drag and drop</p>
                                        </div>
                                        <p className="text-xs text-gray-500">High-resolution PNG, JPG, or GIF up to 10MB</p>
                                    </div>
                                </div>
                                <InputError message={errors.images} className="mt-2" />

                                {/* Image Previews Gallery */}
                                {(existingImages.length > 0 || imagePreviews.length > 0) && (
                                    <div className="mt-4 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                                        {/* Existing Images */}
                                        {existingImages.map((preview, index) => (
                                            <div key={`existing-${index}`} className="relative group rounded-xl overflow-hidden border border-gray-200 shadow-lg">
                                                <img 
                                                    src={preview} 
                                                    alt={`Existing Image ${index + 1}`} 
                                                    className="h-28 w-full object-cover" 
                                                />
                                                <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                                                    <button
                                                        type="button"
                                                        onClick={() => handleRemoveExistingImage(index)}
                                                        className="bg-red-600 text-white rounded-full p-2 hover:bg-red-700 transition-colors shadow-xl"
                                                        title="Remove existing image"
                                                    >
                                                        <XMarkIcon className="h-5 w-5" />
                                                    </button>
                                                </div>
                                                <span className="absolute bottom-0 left-0 bg-gray-900/70 text-white text-xs px-2 py-0.5 rounded-tr-lg">
                                                    Existing
                                                </span>
                                            </div>
                                        ))}
                                        {/* New Image Previews */}
                                        {imagePreviews.map((preview, index) => (
                                            <div key={`new-${index}`} className="relative group rounded-xl overflow-hidden border border-emerald-400 shadow-lg ring-2 ring-emerald-300 ring-offset-2">
                                                <img 
                                                    src={preview} 
                                                    alt={`New Image Preview ${index + 1}`} 
                                                    className="h-28 w-full object-cover" 
                                                />
                                                <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                                                    <button
                                                        type="button"
                                                        onClick={() => handleRemoveNewImage(index)}
                                                        className="bg-red-600 text-white rounded-full p-2 hover:bg-red-700 transition-colors shadow-xl"
                                                        title="Remove new image"
                                                    >
                                                        <XMarkIcon className="h-5 w-5" />
                                                    </button>
                                                </div>
                                                <span className="absolute bottom-0 left-0 bg-emerald-600 text-white text-xs px-2 py-0.5 rounded-tr-lg">
                                                    New
                                                </span>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </FormSection>

                            {/* --- Action Buttons (Fixed Footer-like style) --- */}
                            <div className="flex items-center justify-end space-x-4 pt-8 border-t border-gray-200">
                                {/* Cancel/Back Button (Secondary/Outline Style) */}
                                <Link
                                    href={route('admin.events.index')}
                                    className="px-6 py-2.5 text-sm font-semibold text-gray-700 bg-white border border-gray-300 rounded-lg shadow-sm hover:bg-gray-50 transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500"
                                >
                                    Cancel
                                </Link>
                                
                                {/* Primary Save Button (Emerald Style) */}
                                <PrimaryButton disabled={processing} className="px-6 py-2.5 bg-emerald-600 hover:bg-emerald-700 focus:ring-emerald-500 shadow-md">
                                    <PencilSquareIcon className="w-5 h-5 mr-1.5" />
                                    {processing ? 'Saving Changes...' : 'Save Changes'}
                                </PrimaryButton>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}