import React, { useState } from 'react';
import AdminLayout from '@/Layouts/AdminLayout';
import { Head, useForm } from '@inertiajs/react';
import InputLabel from '@/Components/InputLabel';
import TextInput from '@/Components/TextInput';
import InputError from '@/Components/InputError';
import PrimaryButton from '@/Components/PrimaryButton';
import { 
    PhotoIcon, 
    XMarkIcon, 
    CurrencyDollarIcon, 
    CubeIcon, 
    TagIcon, 
    DocumentTextIcon, 
    SwatchIcon, // New icon for category
    SparklesIcon, // Icon for digital product
    LinkIcon // Icon for URL
} from '@heroicons/react/24/outline';

// Tailwind class for consistent input styling
const inputClass = "mt-1 block w-full border-gray-300 focus:border-emerald-500 focus:ring-emerald-500 rounded-lg shadow-sm transition duration-150 ease-in-out";

export default function Create({ auth, categories }) {

    const { data, setData, post, processing, errors, reset } = useForm({

        name: '',

        description: '',

        price: '',

        stock: '',

        category: '',

        images: null,

        image_urls: [],

        is_digital: false,

    });



    const [imagePreviews, setImagePreviews] = useState([]);



    const handleImageChange = (e) => {

        const files = e.target.files;

        setData('images', files);



        const newPreviews = [];

        for (let i = 0; i < files.length; i++) {

            const reader = new FileReader();

            reader.onloadend = () => {

                newPreviews.push(reader.result);

                if (newPreviews.length === files.length) {

                    setImagePreviews(prev => [...prev, ...newPreviews]);

                }

            };

            reader.readAsDataURL(files[i]);

        }

    };



    const handleUrlAdd = () => {

        const url = prompt('Enter image URL');

        if (url) {

            setData('image_urls', [...data.image_urls, url]);

            setImagePreviews(prev => [...prev, url]);

        }

    };

    

    const removeImage = (index) => {

        const newPreviews = imagePreviews.filter((_, i) => i !== index);

        setImagePreviews(newPreviews);



        const removedPreview = imagePreviews[index];

        if (data.image_urls.includes(removedPreview)) {

            setData('image_urls', data.image_urls.filter(url => url !== removedPreview));

        } else {

            const dt = new DataTransfer();

            const files = Array.from(data.images);

            let fileIndex = -1;

            for(let i = 0; i < files.length; i++) {

                const reader = new FileReader();

                reader.onloadend = () => {

                    if(reader.result === removedPreview) {

                        fileIndex = i;

                        if (fileIndex > -1) {

                            files.splice(fileIndex, 1);

                            files.forEach(file => dt.items.add(file));

                            setData('images', dt.files);

                        }

                    }

                };

                reader.readAsDataURL(files[i]);

            }

        }

    };



    const submit = (e) => {

        e.preventDefault();

        post(route('admin.products.store'), {

            forceFormData: true, // Crucial for Inertia file uploads

            onSuccess: () => {

                reset();

                setImagePreviews([]); // Also reset previews on success

            },

        });

    };



    return (

        <AdminLayout 

            user={auth.user} 

            header={<h1 className="text-3xl font-bold text-gray-900">✨ Create New Product</h1>} // Larger, bolder header

        >

            <Head title="Add New Product" />



            <div className="py-6">

                <div className="max-w-6xl mx-auto sm:px-6 lg:px-8"> {/* Wider container */}

                    <form onSubmit={submit} className="flex flex-col lg:flex-row gap-8">

                        

                        {/* --- LEFT COLUMN: Primary Details (70% width on large screens) --- */}

                        <div className="lg:w-2/3 space-y-8">

                            

                            {/* Section 1: Basic Information */}

                            <div className="bg-white p-8 shadow-xl rounded-xl border border-gray-100">

                                <h3 className="flex items-center text-xl font-semibold text-gray-800 pb-4 mb-4 border-b border-gray-200">

                                    <DocumentTextIcon className="w-6 h-6 mr-2 text-emerald-500" />

                                    Product Details

                                </h3>

                                

                                <div className="space-y-6">

                                    <div>

                                        <InputLabel htmlFor="name" value="Product Name" />

                                        <TextInput

                                            id="name"

                                            type="text"

                                            name="name"

                                            value={data.name}

                                            className={inputClass}

                                            isFocused={true}

                                            onChange={(e) => setData('name', e.target.value)}

                                            placeholder="e.g., Premium Leather Wallet"

                                            required

                                        />

                                        <InputError message={errors.name} className="mt-2" />

                                    </div>

                                    

                                    <div>

                                        <InputLabel htmlFor="description" value="Description" />

                                        <textarea

                                            id="description"

                                            name="description"

                                            value={data.description}

                                            rows="5"

                                            className={`${inputClass} resize-none`}

                                            onChange={(e) => setData('description', e.target.value)}

                                            placeholder="Provide a detailed description of the product features and benefits."

                                        ></textarea>

                                        <InputError message={errors.description} className="mt-2" />

                                    </div>

                                    

                                    <div>

                                        <InputLabel htmlFor="category" value="Category" />

                                        <div className="relative">

                                            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">

                                                <SwatchIcon className="h-5 w-5 text-gray-400" />

                                            </div>

                                            <select

                                                id="category"

                                                name="category"

                                                value={data.category}

                                                className={`${inputClass} pl-10`}

                                                onChange={(e) => setData('category', e.target.value)}

                                            >

                                                <option value="">Select a category</option>

                                                {categories && categories.map((cat) => (

                                                    <option key={cat.id || cat.name} value={cat.name}>

                                                        {cat.name}

                                                    </option>

                                                ))}

                                            </select>

                                        </div>

                                        <InputError message={errors.category} className="mt-2" />

                                    </div>

                                </div>

                            </div>



                            {/* Section 3: Product Images */}

                            <div className="bg-white p-8 shadow-xl rounded-xl border border-gray-100">

                                <div className="flex justify-between items-center pb-4 mb-4 border-b border-gray-200">

                                    <h3 className="flex items-center text-xl font-semibold text-gray-800">

                                        <PhotoIcon className="w-6 h-6 mr-2 text-emerald-500" />

                                        Product Images

                                    </h3>

                                    <button type="button" onClick={handleUrlAdd} className="flex items-center text-sm font-medium text-emerald-600 hover:text-emerald-500">

                                        <LinkIcon className="w-4 h-4 mr-1" />

                                        Add from URL

                                    </button>

                                </div>

                                

                                <div className="mt-2 flex justify-center px-6 pt-8 pb-8 border-2 border-dashed rounded-xl border-gray-300 hover:border-emerald-400 transition-colors bg-gray-50/50">

                                    <div className="space-y-1 text-center">

                                        <PhotoIcon className="mx-auto h-12 w-12 text-gray-400" />

                                        <div className="flex text-sm text-gray-600 justify-center">

                                            <label

                                                htmlFor="images"

                                                className="relative cursor-pointer bg-white rounded-md font-medium text-emerald-600 hover:text-emerald-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-emerald-500 px-2"

                                            >

                                                <span>Upload files</span>

                                                <input 

                                                    id="images" 

                                                    name="images[]" 

                                                    type="file" 

                                                    multiple 

                                                    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 10MB each. Max 5 images.</p>

                                    </div>

                                </div>

                                <InputError message={errors.images} className="mt-2" />



                                {/* Image Previews (Enhanced styling) */}

                                {imagePreviews.length > 0 && (

                                    <div className="mt-6 grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-4">

                                        {imagePreviews.map((preview, index) => (

                                            <div key={index} className="relative group shadow-lg rounded-lg overflow-hidden border border-gray-200">

                                                <img src={preview} alt={`Preview ${index + 1}`} className="h-20 w-full object-cover" />

                                                <div className="absolute inset-0 bg-black bg-opacity-30 group-hover:bg-opacity-50 transition duration-300 flex items-center justify-center">

                                                    <button

                                                        type="button"

                                                        onClick={() => removeImage(index)}

                                                        className="absolute top-1 right-1 bg-red-600 text-white rounded-full p-1.5 opacity-0 group-hover:opacity-100 transition-opacity transform group-hover:scale-100 scale-90"

                                                        aria-label="Remove image"

                                                    >

                                                        <XMarkIcon className="h-4 w-4" />

                                                    </button>

                                                </div>

                                            </div>

                                        ))}

                                    </div>

                                )}

                            </div>

                        </div>



                        {/* --- RIGHT COLUMN: Pricing & Settings (30% width on large screens) --- */}

                        <div className="lg:w-1/3 space-y-8">

                             {/* Section 2: Pricing & Inventory */}

                            <div className="bg-white p-6 shadow-xl rounded-xl border border-gray-100">

                                <h3 className="flex items-center text-xl font-semibold text-gray-800 pb-4 mb-4 border-b border-gray-200">

                                    <CurrencyDollarIcon className="w-6 h-6 mr-2 text-emerald-500" />

                                    Pricing & Stock

                                </h3>

                                <div className="space-y-5">

                                    <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" />

                                            </div>

                                            <TextInput

                                                id="price"

                                                type="number"

                                                name="price"

                                                value={data.price}

                                                className="mt-1 block w-full pl-10 rounded-lg"

                                                onChange={(e) => setData('price', e.target.value)}

                                                required

                                                step="0.01"

                                                min="0"

                                            />

                                        </div>

                                        <InputError message={errors.price} className="mt-2" />

                                    </div>

                                    

                                    <div>

                                        <InputLabel htmlFor="stock" value="Stock Quantity" />

                                        <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">

                                                <CubeIcon className="h-5 w-5 text-gray-400" />

                                            </div>

                                            <TextInput

                                                id="stock"

                                                type="number"

                                                name="stock"

                                                value={data.stock}

                                                className="mt-1 block w-full pl-10 rounded-lg"

                                                onChange={(e) => setData('stock', e.target.value)}

                                                required={!data.is_digital}

                                                min="0"

                                                disabled={data.is_digital}

                                            />

                                        </div>

                                        {data.is_digital && <p className="mt-1 text-xs text-gray-500 flex items-center"><SparklesIcon className="w-4 h-4 mr-1"/> Stock disabled for digital product.</p>}

                                        <InputError message={errors.stock} className="mt-2" />

                                    </div>



                                    {/* Digital Product Checkbox */}

                                    <div className="pt-2">

                                        <label className="flex items-center space-x-2 p-3 border border-gray-200 rounded-lg hover:bg-emerald-50/50 cursor-pointer transition-colors">

                                            <input

                                                type="checkbox"

                                                name="is_digital"

                                                checked={data.is_digital}

                                                onChange={(e) => {

                                                    setData('is_digital', e.target.checked);

                                                    if (e.target.checked) {

                                                        // Clear stock when switching to digital

                                                        setData('stock', '');

                                                    }

                                                }}

                                                className="rounded border-gray-300 text-emerald-600 shadow-sm focus:border-emerald-500 focus:ring focus:ring-emerald-500 focus:ring-opacity-50"

                                            />

                                            <span className="text-sm font-medium text-gray-700 flex items-center">

                                                <SparklesIcon className="h-5 w-5 mr-1 text-emerald-500"/>

                                                Digital Product

                                            </span>

                                        </label>

                                    </div>

                                </div>

                            </div>

                        </div>

                    

                        {/* --- Action Buttons (Fixed Footer-like position) --- */}

                        <div className="lg:fixed lg:bottom-0 lg:left-0 lg:right-0 bg-white border-t border-gray-200 p-4 shadow-2xl z-10">

                            <div className="max-w-6xl mx-auto flex justify-end space-x-4">

                                <button

                                    type="button"

                                    onClick={() => reset()}

                                    className="px-6 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg shadow-sm hover:bg-gray-50 transition duration-150 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500"

                                >

                                    Cancel

                                </button>

                                <PrimaryButton 

                                    disabled={processing} 

                                    className="px-6 py-2 bg-emerald-600 hover:bg-emerald-700 focus:ring-emerald-500 transition duration-150"

                                >

                                    {processing ? 'Saving Product...' : 'Save Product'}

                                </PrimaryButton>

                            </div>

                        </div>



                    </form>

                </div>

            </div>

        </AdminLayout>

    );

}
