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, PencilSquareIcon } from '@heroicons/react/24/outline';

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({ post: postData, auth }) {
    const [imagePreview, setImagePreview] = useState(postData.image_url || null);

    const { data, setData, post, processing, errors } = useForm({
        title: postData.title || '',
        content: postData.content || '',
        image: null,
        _method: 'put',
    });

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

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

    const submit = (e) => {
        e.preventDefault();
        post(route('admin.posts.update', postData.id), {
            forceFormData: true,
        });
    };

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

            <div className="py-8">
                <div className="max-w-6xl mx-auto sm:px-6 lg:px-8">
                    <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.posts.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 Posts List
                            </Link>
                            <h1 className="mt-2 text-3xl font-extrabold leading-7 text-gray-900 sm:text-4xl sm:truncate">
                                Editing: **{postData.title}**
                            </h1>
                        </div>
                    </div>

                    <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">
                            <FormSection
                                title="Post Content"
                                description="Edit the title and content of your blog post."
                            >
                                <div>
                                    <InputLabel htmlFor="title" value="Post 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="content" value="Post Content" />
                                    <textarea
                                        id="content"
                                        value={data.content}
                                        rows="10"
                                        className="mt-1 block w-full border-gray-300 focus:border-emerald-500 focus:ring-emerald-500 rounded-lg shadow-sm"
                                        onChange={(e) => setData('content', e.target.value)}
                                    ></textarea>
                                    <InputError message={errors.content} className="mt-2" />
                                </div>
                            </FormSection>

                            <FormSection
                                title="Post Image"
                                description="Upload a new featured image for your post."
                            >
                                <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="image"
                                                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 a file</span>
                                                <input id="image" name="image" type="file" 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">PNG, JPG, GIF up to 2MB</p>
                                    </div>
                                </div>
                                <InputError message={errors.image} className="mt-2" />

                                {imagePreview && (
                                    <div className="mt-4 relative">
                                        <img src={imagePreview} alt="Image Preview" className="h-48 w-full object-cover rounded-lg" />
                                        <button
                                            type="button"
                                            onClick={handleRemoveImage}
                                            className="absolute top-2 right-2 bg-red-600 text-white rounded-full p-1 hover:bg-red-700 transition-colors"
                                        >
                                            <XMarkIcon className="h-4 w-4" />
                                        </button>
                                    </div>
                                )}
                            </FormSection>

                            <div className="flex items-center justify-end space-x-4 pt-8 border-t border-gray-200">
                                <Link
                                    href={route('admin.posts.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>
                                <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>
    );
}
