import { useState } 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, 
    BookOpenIcon, 
    PhotoIcon,
    TicketIcon,
    XMarkIcon,
    PlusCircleIcon 
} from '@heroicons/react/24/outline';
import { showErrorToast, showSuccessToast } from '@/Components/ToastNote';

// --- Reusable Component: FormSection (Styled for clarity) ---
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">
                <BookOpenIcon className="w-6 h-6 mr-2 text-indigo-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 Create({ auth, doctors }) {
    const { data, setData, post, processing, errors, reset } = useForm({
        name: '',
        description: '',
        type: 'paid', // Added: Default to paid, common for school services
        price: '',
        start_date: '',
        duration: '',
        location: '',
        instructor_id: '',
        images: [], // Changed: For multiple image files
    });

    const [imagePreviews, setImagePreviews] = useState([]); // Changed: For multiple image previews

    const handleImageChange = (e) => {
        const files = Array.from(e.target.files);
        if (files.length > 0) {
            // Append new files to existing ones
            setData('images', [...data.images, ...files]);

            // Generate previews for new files
            const newPreviews = files.map(file => {
                return new Promise((resolve) => {
                    const reader = new FileReader();
                    reader.onload = (e) => resolve(e.target.result);
                    reader.readAsDataURL(file);
                });
            });
            
            Promise.all(newPreviews).then(results => {
                setImagePreviews(prevPreviews => [...prevPreviews, ...results]);
            });
        }
    };

    const handleRemoveImage = (indexToRemove) => {
        // Remove from data.images
        const newImages = data.images.filter((_, index) => index !== indexToRemove);
        setData('images', newImages);

        // Remove from imagePreviews
        const newImagePreviews = imagePreviews.filter((_, index) => index !== indexToRemove);
        setImagePreviews(newImagePreviews);

        // If no images left, clear the file input visually
        if (newImages.length === 0) {
            document.getElementById('images').value = ''; 
        }
    };

    const submit = (e) => {
        e.preventDefault();
        post(route('admin.school-services.store'), {
            forceFormData: true, // Crucial for file uploads
            onSuccess: () => {
                showSuccessToast('Service updated successfully.');
            },
            onError: (errors) => {
                // Prefer the first validation message if present
                let message = 'Failed to update service.';
                if (errors && typeof errors === 'object') {
                    const first = Object.values(errors)[0];
                    if (Array.isArray(first)) message = first[0];
                    else if (typeof first === 'string') message = first;
                }
                showErrorToast(message);
            },
        }
    );
    };

    return (
        <AdminLayout
            user={auth.user}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Add New School Service</h2>}
        >
            <Head title="Add New School Service" />

            <div className="py-8">
                <div className="mx-auto sm:px-6 lg:px-8">
                    
                    {/* --- 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.school-services.index')} 
                                className="inline-flex items-center text-sm font-medium text-gray-500 hover:text-indigo-600 transition duration-150"
                            >
                                <ArrowLeftIcon className="-ml-0.5 mr-1 h-5 w-5" aria-hidden="true" />
                                Back to Services List
                            </Link>
                            <h1 className="mt-2 text-3xl font-extrabold leading-7 text-gray-900 sm:text-4xl sm:truncate">
                                **Register a New School Service** 📝
                            </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: Service Details */}
                            <FormSection 
                                title="Service Core Information"
                                description="Provide the name and a detailed explanation of the service offered to students/parents."
                            >
                                <div>
                                    <InputLabel htmlFor="name" value="Service Name" />
                                    <TextInput
                                        id="name"
                                        type="text"
                                        name="name"
                                        value={data.name}
                                        placeholder="E.g., After-School Tutoring, School Bus Pass, Yearbook Fee"
                                        className="mt-1 block w-full rounded-lg border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 shadow-sm"
                                        onChange={(e) => setData('name', e.target.value)}
                                        required
                                        isFocused={true}
                                    />
                                    <InputError message={errors.name} className="mt-2" />
                                </div>
                                <div>
                                    <InputLabel htmlFor="description" value="Service Description" />
                                    <textarea
                                        id="description"
                                        name="description"
                                        value={data.description}
                                        rows="4"
                                        placeholder="Describe the benefits, schedule, and any prerequisites for this service."
                                        className="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-lg shadow-sm"
                                        onChange={(e) => setData('description', e.target.value)}
                                    ></textarea>
                                    <InputError message={errors.description} className="mt-2" />
                                </div>
                            </FormSection>

                            {/* Section 2: Pricing and Type */}
                            <FormSection 
                                title="Pricing and Availability"
                                description="Set the type of service (Free or Paid) and the associated cost."
                            >
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                                    {/* Service Type Select */}
                                    <div>
                                        <InputLabel htmlFor="type" value="Service 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-indigo-500 focus:ring-indigo-500 rounded-lg shadow-sm"
                                                onChange={(e) => setData('type', e.target.value)}
                                            >
                                                <option value="paid">Paid Service</option>
                                                <option value="free">Free Service</option>
                                            </select>
                                        </div>
                                        <InputError message={errors.type} className="mt-2" />
                                    </div>
                                    
                                    {/* Price Field (Conditional) */}
                                    {data.type === 'paid' && (
                                        <div>
                                            <InputLabel htmlFor="price" value="Service Price (GHS)" />
                                            <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">
                                                    <span className="text-gray-500">₵</span>
                                                </div>
                                                <TextInput
                                                    id="price"
                                                    type="number"
                                                    name="price"
                                                    value={data.price}
                                                    placeholder="10.00"
                                                    className="mt-1 block w-full pl-10 rounded-lg border-gray-300 focus:border-indigo-500 focus:ring-indigo-500"
                                                    onChange={(e) => setData('price', e.target.value)}
                                                    required={data.type === 'paid'}
                                                    step="0.01"
                                                />
                                            </div>
                                            <InputError message={errors.price} className="mt-2" />
                                        </div>
                                    )}
                                </div>
                            </FormSection>

                            {/* Section 3: Schedule and Location */}
                            <FormSection 
                                title="Schedule and Location"
                                description="Specify the start date, duration, and physical or virtual location of the service."
                            >
                                <div>
                                    <InputLabel htmlFor="start_date" value="Start Date" />
                                    <TextInput
                                        id="start_date"
                                        type="date"
                                        name="start_date"
                                        value={data.start_date}
                                        className="mt-1 block w-full rounded-lg border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 shadow-sm"
                                        onChange={(e) => setData('start_date', e.target.value)}
                                    />
                                    <InputError message={errors.start_date} className="mt-2" />
                                </div>
                                <div>
                                    <InputLabel htmlFor="duration" value="Duration" />
                                    <TextInput
                                        id="duration"
                                        type="text"
                                        name="duration"
                                        value={data.duration}
                                        placeholder="E.g., 10 weeks, 3 months, 1 hour"
                                        className="mt-1 block w-full rounded-lg border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 shadow-sm"
                                        onChange={(e) => setData('duration', e.target.value)}
                                    />
                                    <InputError message={errors.duration} className="mt-2" />
                                </div>
                                <div>
                                    <InputLabel htmlFor="location" value="Location" />
                                    <TextInput
                                        id="location"
                                        type="text"
                                        name="location"
                                        value={data.location}
                                        placeholder="E.g., Online, School Hall, Room 101"
                                        className="mt-1 block w-full rounded-lg border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 shadow-sm"
                                        onChange={(e) => setData('location', e.target.value)}
                                    />
                                    <InputError message={errors.location} className="mt-2" />
                                </div>
                            </FormSection>

                            {/* Section 4: Instructor */}
                            <FormSection 
                                title="Instructor Assignment"
                                description="Assign a qualified instructor (doctor) to this school service."
                            >
                                <div>
                                    <InputLabel htmlFor="instructor_id" value="Instructor" />
                                    <select
                                        id="instructor_id"
                                        name="instructor_id"
                                        value={data.instructor_id}
                                        className="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-lg shadow-sm"
                                        onChange={(e) => setData('instructor_id', e.target.value)}
                                    >
                                        <option value="">Select an Instructor</option>
                                        {doctors.map((doctor) => (
                                            <option key={doctor.id} value={doctor.id}>
                                                {doctor.name}
                                            </option>
                                        ))}
                                    </select>
                                    <InputError message={errors.instructor_id} className="mt-2" />
                                </div>
                            </FormSection>

                            {/* Section 5: Service Images */}
                            <FormSection 
                                title="Service Images"
                                description="Upload multiple images to represent the service on the dashboard and public portal."
                            >
                                
                                {imagePreviews.length > 0 ? (
                                    /* Image Previews and Remove Buttons */
                                    <div className="mt-2 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
                                        {imagePreviews.map((preview, index) => (
                                            <div key={index} className="relative rounded-xl overflow-hidden border border-indigo-400 shadow-lg ring-2 ring-indigo-300 ring-offset-2">
                                                <img 
                                                    src={preview} 
                                                    alt={`Service Image Preview ${index + 1}`} 
                                                    className="h-32 w-full object-cover" 
                                                />
                                                <button
                                                    type="button"
                                                    onClick={() => handleRemoveImage(index)}
                                                    className="absolute top-2 right-2 bg-red-600 text-white rounded-full p-1.5 hover:bg-red-700 transition-colors shadow-xl z-10"
                                                    title="Remove image"
                                                >
                                                    <XMarkIcon className="h-5 w-5" />
                                                </button>
                                            </div>
                                        ))}
                                    </div>
                                ) : null}

                                {/* File Input/Drop Area */}
                                <div className="mt-2 flex justify-center px-6 pt-5 pb-6 border-2 border-indigo-300 border-dashed rounded-lg hover:border-indigo-400 transition-colors bg-indigo-50/50">
                                    <div className="space-y-1 text-center">
                                        <PhotoIcon className="mx-auto h-12 w-12 text-indigo-500" />
                                        <div className="flex text-sm text-gray-600">
                                            <label
                                                htmlFor="images"
                                                className="relative cursor-pointer bg-white rounded-md font-medium text-indigo-600 hover:text-indigo-700 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500"
                                            >
                                                <span>Upload files</span>
                                                <input 
                                                    id="images" 
                                                    name="images[]" 
                                                    type="file" 
                                                    className="sr-only" 
                                                    onChange={handleImageChange} 
                                                    accept="image/*"
                                                    multiple // Added multiple attribute
                                                />
                                            </label>
                                            <p className="pl-1 text-gray-500">or drag and drop</p>
                                        </div>
                                        <p className="text-xs text-gray-500">PNG, JPG, up to 5MB each.</p>
                                    </div>
                                </div>
                                <InputError message={errors.images} className="mt-2" />
                            </FormSection>


                            {/* --- Action Buttons --- */}
                            <div className="flex items-center justify-end space-x-4 pt-8 border-t border-gray-200">
                                <Link
                                    href={route('admin.school-services.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-indigo-500"
                                >
                                    Cancel
                                </Link>
                                <PrimaryButton 
                                    disabled={processing} 
                                    className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 focus:ring-indigo-500 shadow-md"
                                >
                                    <PlusCircleIcon className="w-5 h-5 mr-1.5" />
                                    {processing ? 'Saving...' : 'Save Service'}
                                </PrimaryButton>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}