import React, { useState, useEffect } from 'react';
import AdminLayout from '@/Layouts/AdminLayout';
import { Head, 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';
import { Link } from '@inertiajs/react';
import { PhotoIcon, XMarkIcon, ChevronLeftIcon } from '@heroicons/react/24/outline'; 
import Checkbox from '@/Components/Checkbox'; // Assuming you have a Checkbox component
import { showErrorToast, showInfoToast } from '@/Components/ToastNote';

export default function ServiceEdit({ service }) {
    // State for icon and image previews, initialized with service data
    const [iconPreview, setIconPreview] = useState(service.icon || '');
    const [imagePreview, setImagePreview] = useState(service.image_url || null);

    const { data, setData, post, processing, errors } = useForm({
        _method: 'post', // Key for Inertia PUT method spoofing
        title: service.title || '',
        description: service.description || '',
        icon: service.icon || '',
        order: service.order || 0,
        is_visible: service.is_visible ?? true,
        image: null, // Holds the new file object for upload
        type: service.type || 'paid',
        price: service.price || 0,
    });

    // Re-initialize form data when the 'service' prop changes (useful if this component is reused)
    useEffect(() => {
        setData({
            _method: 'put',
            title: service.title || '',
            description: service.description || '',
            icon: service.icon || '',
            order: service.order || 0,
            is_visible: service.is_visible ?? true,
            image: null,
            type: service.type || 'paid',
            price: service.price || 0,
        });
        setIconPreview(service.icon || '');
        setImagePreview(service.image_url || null);
    }, [service]);

    const handleIconChange = (e) => {
        const iconValue = e.target.value;
        setData('icon', iconValue);
        setIconPreview(iconValue);
    };

    const handleImageChange = (e) => {
        const file = e.target.files[0];
        setData('image', file);

        if (file) {
            const reader = new FileReader();
            reader.onloadend = () => {
                setImagePreview(reader.result);
            };
            reader.readAsDataURL(file);
        } else {
            setImagePreview(null);
        }
    };

    // Remove the newly selected image/current image from preview and form data
    const removeImage = () => {
        setData('image', null);
        setImagePreview(null);
    };

    const submit = (e) => {
        e.preventDefault();
        post(route('admin.services.update', service.id), {
            onSuccess: () => {
                showInfoToast("Service updated successfully");
            },
            onError: (errors) => {
                showErrorToast('Please correct the errors in the form.');
            }
        });
    };

    // Common icon suggestions
    const iconSuggestions = [
        '🚀', '💼', '📊', '🔧', '💻', '🎨', '📱',
        '🔒', '🌐', '📈', '💡', '🔍', '🛠️', '📝'
    ];

    return (
        <AdminLayout>
            <Head title={`Edit Service: ${service.title}`} />

            <div className="py-8 px-4 sm:px-6 lg:px-8">
                <div className="mx-auto">
                    {/* --- Header Section --- */}
                    <header className="mb-6">
                        <Link 
                            href={route('admin.services.index')} 
                            className="text-sm font-medium text-indigo-600 hover:text-indigo-500 flex items-center mb-2 transition-colors"
                        >
                            <ChevronLeftIcon className="w-4 h-4 mr-1" />
                            Back to Services
                        </Link>
                        <h1 className="text-3xl font-extrabold text-gray-900">Edit Service: {service.title}</h1>
                        <p className="mt-1 text-base text-gray-500">
                            Update the content, media, and visibility settings for this service.
                        </p>
                    </header>
                    
                    <form onSubmit={submit} className="space-y-8">
                        <div className="lg:grid lg:grid-cols-3 lg:gap-8">
                            
                            {/* --- Column 1: Core Content and Metadata --- */}
                            <div className="lg:col-span-2 space-y-8">
                                
                                {/* 1. General Information Card */}
                                <div className="bg-white shadow-xl rounded-xl p-6 border border-gray-100">
                                    <h2 className="text-xl font-semibold text-gray-800 border-b pb-3 mb-5">Service Content</h2>
                                    
                                    <div className="space-y-5">
                                        <div>
                                            <InputLabel htmlFor="title" value="Service Title" className="mb-1" />
                                            <TextInput
                                                id="title"
                                                type="text"
                                                name="title"
                                                value={data.title}
                                                className="block w-full"
                                                placeholder="e.g., Web Development"
                                                isFocused={true}
                                                onChange={(e) => setData('title', e.target.value)}
                                            />
                                            <p className="mt-1 text-sm text-gray-500">A clear, concise name for your service.</p>
                                            <InputError message={errors.title} className="mt-2" />
                                        </div>

                                        <div>
                                            <InputLabel htmlFor="description" value="Service Description" className="mb-1" />
                                            <textarea
                                                id="description"
                                                name="description"
                                                rows={5}
                                                value={data.description}
                                                className="block w-full border-gray-300 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
                                                placeholder="Describe your service in detail..."
                                                onChange={(e) => setData('description', e.target.value)}
                                            ></textarea>
                                            <p className="mt-1 text-sm text-gray-500">Provide a detailed description of what this service includes (max 200 words recommended).</p>
                                            <InputError message={errors.description} className="mt-2" />
                                        </div>
                                    </div>
                                </div> {/* End General Info Card */}
                                
                                {/* 2. Icon Picker Card */}
                                <div className="bg-white shadow-xl rounded-xl p-6 border border-gray-100">
                                    <h2 className="text-xl font-semibold text-gray-800 border-b pb-3 mb-5">Icon Selection</h2>
                                    
                                    <div>
                                        <InputLabel htmlFor="icon" value="Service Icon (Emoji or Class)" className="mb-1" />
                                        <div className="mt-1 flex rounded-lg shadow-sm">
                                            <TextInput
                                                id="icon"
                                                type="text"
                                                name="icon"
                                                value={data.icon}
                                                className="flex-1 min-w-0 block w-full rounded-l-lg"
                                                placeholder="e.g., 🚀 or fa-rocket"
                                                onChange={handleIconChange}
                                            />
                                            <div className="inline-flex items-center px-4 rounded-r-lg border border-l-0 border-gray-300 bg-gray-50 text-gray-500 text-3xl font-bold">
                                                {iconPreview || <span className="text-gray-400 text-sm">Preview</span>}
                                            </div>
                                        </div>
                                        <p className="mt-1 text-sm text-gray-500">Paste an **emoji** or **icon class name** (Font Awesome, Heroicons, etc.) here.</p>
                                        <InputError message={errors.icon} className="mt-2" />

                                        {/* Icon Suggestions */}
                                        <div className="mt-4">
                                            <p className="text-sm font-semibold text-gray-700 mb-2">Quick Pick Emojis:</p>
                                            <div className="flex flex-wrap gap-2">
                                                {iconSuggestions.map((icon, index) => (
                                                    <button
                                                        key={index}
                                                        type="button"
                                                        onClick={() => {
                                                            setData('icon', icon);
                                                            setIconPreview(icon);
                                                        }}
                                                        title={`Select ${icon}`}
                                                        className={`inline-flex items-center p-2 text-xl border shadow-sm rounded-lg transition duration-150 ease-in-out ${data.icon === icon ? 'border-indigo-500 ring-2 ring-indigo-500 bg-indigo-50' : 'border-gray-300 bg-white hover:bg-gray-50'}`}
                                                    >
                                                        {icon}
                                                    </button>
                                                ))}
                                            </div>
                                        </div>
                                    </div>
                                </div> {/* End Icon Picker Card */}
                            </div>
                            
                            {/* --- Column 2: Media and Settings --- */}
                            <div className="lg:col-span-1 space-y-8 mt-8 lg:mt-0">
                                
                                {/* 3. Image Upload Card */}
                                <div className="bg-white shadow-xl rounded-xl p-6 border border-gray-100">
                                    <h2 className="text-xl font-semibold text-gray-800 border-b pb-3 mb-5">Service Image</h2>
                                    
                                    <div>
                                        <InputLabel htmlFor="image" value="Featured Image" className="mb-1" />
                                        
                                        <div className="mt-2 flex justify-center w-full min-h-[10rem] px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-indigo-400 transition-colors relative">
                                            <div className="space-y-1 text-center">
                                                {imagePreview ? (
                                                    <div className="relative w-full h-auto min-h-[10rem] group">
                                                        <img 
                                                            src={imagePreview} 
                                                            alt="Image Preview" 
                                                            className="w-full max-h-48 object-contain rounded-md" 
                                                        />
                                                        <button
                                                            type="button"
                                                            onClick={removeImage}
                                                            title="Remove Image"
                                                            className="absolute top-0 right-0 transform -translate-y-1/2 translate-x-1/2 bg-red-600 text-white rounded-full p-1 shadow-lg hover:bg-red-700 transition"
                                                        >
                                                            <XMarkIcon className="h-4 w-4" />
                                                        </button>
                                                    </div>
                                                ) : (
                                                    <>
                                                        <PhotoIcon className="mx-auto h-12 w-12 text-gray-400" />
                                                        <div className="flex text-sm text-gray-600 justify-center">
                                                            <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} accept="image/*" />
                                                            </label>
                                                            <p className="pl-1">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" />
                                    </div>
                                </div> {/* End Image Upload Card */}
                                
                                {/* 4. Settings Card */}
                                <div className="bg-white shadow-xl rounded-xl p-6 border border-gray-100">
                                    <h2 className="text-xl font-semibold text-gray-800 border-b pb-3 mb-5">Settings</h2>
                                    
                                    <div className="space-y-5">
                                        <div>
                                            <InputLabel htmlFor="order" value="Display Order" className="mb-1" />
                                            <TextInput
                                                id="order"
                                                type="number"
                                                name="order"
                                                value={data.order}
                                                className="block w-full"
                                                placeholder="0"
                                                onChange={(e) => setData('order', e.target.value)}
                                            />
                                            <p className="mt-1 text-sm text-gray-500">Control the position. Lower numbers appear first.</p>
                                            <InputError message={errors.order} className="mt-2" />
                                        </div>

                                        <div>
                                            <InputLabel htmlFor="type" value="Service Type" className="mb-1" />
                                            <select
                                                id="type"
                                                name="type"
                                                value={data.type}
                                                className="block w-full border-gray-300 rounded-lg shadow-sm focus:ring-indigo-500 focus:border-indigo-500"
                                                onChange={(e) => setData('type', e.target.value)}
                                            >
                                                <option value="paid">Paid</option>
                                                <option value="free">Free</option>
                                            </select>
                                            <p className="mt-1 text-sm text-gray-500">Specify if this service is paid or free.</p>
                                            <InputError message={errors.type} className="mt-2" />
                                        </div>

                                        <div>
                                            <InputLabel htmlFor="price" value="Service Price" className="mb-1" />
                                            <TextInput
                                                id="price"
                                                type="number"
                                                name="price"
                                                value={data.price}
                                                className="block w-full"
                                                placeholder="0.00"
                                                onChange={(e) => setData('price', e.target.value)}
                                                step="0.01"
                                                min="0"
                                            />
                                            <p className="mt-1 text-sm text-gray-500">The cost of the service. Set to 0 for free services.</p>
                                            <InputError message={errors.price} className="mt-2" />
                                        </div>
                                        
                                        <div className="flex items-start pt-3">
                                            <div className="flex items-center h-5">
                                                <Checkbox
                                                    id="is_visible"
                                                    name="is_visible"
                                                    checked={data.is_visible}
                                                    onChange={(e) => setData('is_visible', e.target.checked)}
                                                    className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
                                                />
                                            </div>
                                            <div className="ml-3 text-sm">
                                                <label htmlFor="is_visible" className="font-medium text-gray-900">
                                                    Service Visibility
                                                </label>
                                                <p className="text-gray-500">Make this service visible on the public website.</p>
                                            </div>
                                        </div>
                                    </div>
                                </div> {/* End Settings Card */}
                            </div>
                        </div>

                        {/* --- Footer/Action Bar --- */}
                        <div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 shadow-lg z-10">
                            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex justify-end space-x-3">
                                <Link href={route('admin.services.index')}>
                                    <SecondaryButton type="button">Cancel</SecondaryButton>
                                </Link>
                                <PrimaryButton disabled={processing}>
                                    {processing ? 'Saving Changes...' : 'Save Updates'}
                                </PrimaryButton>
                            </div>
                        </div>
                    </form>
                    
                    {/* Placeholder for Spacing when fixed footer is active */}
                    <div className="h-20"></div> 

                </div>
            </div>
        </AdminLayout>
    );
}