import React, { useState, useEffect } from 'react';
import AdminLayout from '@/Layouts/AdminLayout';
import { Head, Link, useForm } from '@inertiajs/react';
import TextInput from '@/Components/TextInput';
import InputLabel from '@/Components/InputLabel';
import InputError from '@/Components/InputError';
import PrimaryButton from '@/Components/PrimaryButton';
import SecondaryButton from '@/Components/SecondaryButton';

export default function GalleryEdit({ gallery }) {
    const [imagePreview, setImagePreview] = useState(gallery.image_url || null);
    const [removeImage, setRemoveImage] = useState(false);

    const { data, setData, post, processing, errors } = useForm({
        title: gallery.title || '',
        description: gallery.description || '',
        image: null,
        order: gallery.order || 0,
        url: gallery.url || '',
        _method: 'put',
    });

    useEffect(() => {
        setData({
            title: gallery.title || '',
            description: gallery.description || '',
            image: null,
            order: gallery.order || 0,
            url: gallery.url || '',
            _method: 'put',
        });
        setImagePreview(gallery.image_url || null);
        setRemoveImage(false);
    }, [gallery]);

    const handleImageChange = (e) => {
        const file = e.target.files[0];
        if (file) {
            setData('image', file);
            setRemoveImage(false);
            const reader = new FileReader();
            reader.onload = () => setImagePreview(reader.result);
            reader.readAsDataURL(file);
        }
    };

    const handleRemoveImage = () => {
        setData('image', null);
        setImagePreview(null);
        setRemoveImage(true);
    };

    const submit = (e) => {
        e.preventDefault();
        post(route('admin.gallery.update', gallery.id), {
            data: {
                ...data,
                remove_image: removeImage
            }
        });
    };

    return (
        <AdminLayout>
            <Head title="Edit Gallery Item" />

            <div className="py-8 px-4 sm:px-6 lg:px-8">
                <div className="max-w-3xl mx-auto">
                    <div className="mb-8">
                        <div className="flex items-center mb-2">
                            <Link href={route('admin.gallery.index')} className="text-sm font-medium text-indigo-600 hover:text-indigo-500 flex items-center">
                                <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                                </svg>
                                Back to Gallery
                            </Link>
                        </div>
                        <h1 className="text-2xl font-bold text-gray-900">Edit Gallery Item</h1>
                        <p className="mt-1 text-sm text-gray-500">
                            Update the details for this gallery item.
                        </p>
                    </div>

                    <div className="bg-white shadow overflow-hidden sm:rounded-lg">
                        <div className="px-4 py-5 sm:px-6 border-b border-gray-200">
                            <h3 className="text-lg leading-6 font-medium text-gray-900">Item Information</h3>
                            <p className="mt-1 max-w-2xl text-sm text-gray-500">
                                Modify the details for your gallery item.
                            </p>
                        </div>
                        
                        <form onSubmit={submit} className="space-y-6 p-6">
                            <div>
                                <InputLabel htmlFor="title" value="Title" />
                                <TextInput
                                    id="title"
                                    type="text"
                                    name="title"
                                    value={data.title}
                                    className="mt-1 block w-full"
                                    placeholder="e.g., Project Alpha"
                                    isFocused={true}
                                    onChange={(e) => setData('title', e.target.value)}
                                />
                                <InputError message={errors.title} className="mt-2" />
                            </div>

                            <div>
                                <InputLabel htmlFor="description" value="Description" />
                                <textarea
                                    id="description"
                                    name="description"
                                    rows={4}
                                    value={data.description}
                                    className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
                                    placeholder="Describe the gallery item..."
                                    onChange={(e) => setData('description', e.target.value)}
                                ></textarea>
                                <InputError message={errors.description} className="mt-2" />
                            </div>

                            <div>
                                <InputLabel htmlFor="order" value="Display Order" />
                                <TextInput
                                    id="order"
                                    type="number"
                                    name="order"
                                    value={data.order}
                                    className="mt-1 block w-full"
                                    placeholder="0"
                                    onChange={(e) => setData('order', e.target.value)}
                                />
                                <InputError message={errors.order} className="mt-2" />
                            </div>

                            <div>
                                <InputLabel htmlFor="image" value="Image" />
                                <div className="mt-1">
                                    {imagePreview ? (
                                        <div className="flex flex-col items-center">
                                            <img src={imagePreview} alt="Item preview" className="max-h-48 rounded-lg mb-4" />
                                            <div className="flex space-x-3">
                                                <label className="cursor-pointer bg-white py-2 px-3 border border-gray-300 rounded-md shadow-sm text-sm leading-4 font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                                    Replace Image
                                                    <input id="image" name="image" type="file" className="sr-only" onChange={handleImageChange} />
                                                </label>
                                                <button
                                                    type="button"
                                                    onClick={handleRemoveImage}
                                                    className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                                                >
                                                    Remove Image
                                                </button>
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                                            <div className="space-y-1 text-center">
                                                <svg className="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
                                                    <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                                </svg>
                                                <div className="flex text-sm text-gray-600">
                                                    <label htmlFor="image" className="relative cursor-pointer bg-white rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500">
                                                        <span>Upload a file</span>
                                                        <input id="image" name="image" type="file" className="sr-only" onChange={handleImageChange} />
                                                    </label>
                                                    <p className="pl-1">or drag and drop</p>
                                                </div>
                                                <p className="text-xs text-gray-500">PNG, JPG, GIF up to 10MB</p>
                                            </div>
                                        </div>
                                    )}
                                </div>
                                <InputError message={errors.image} className="mt-2" />
                            </div>

                            <div className="flex justify-end space-x-3 pt-5 border-t border-gray-200">
                                <Link href={route('admin.gallery.index')}>
                                    <SecondaryButton type="button">Cancel</SecondaryButton>
                                </Link>
                                <PrimaryButton disabled={processing} className="ml-3">
                                    {processing ? 'Updating...' : 'Update Item'}
                                </PrimaryButton>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}
