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';

export default function PortfolioEdit({ portfolio, toast }) {
    const [imagePreview, setImagePreview] = useState(portfolio.image_url || null);
    const [removeImage, setRemoveImage] = useState(false);
    
    const { data, setData, post, processing, errors } = useForm({
        title: portfolio.title || '',
        description: portfolio.description || '',
        image: null,
        link: portfolio.link || '',
        order: portfolio.order || 0,
        is_featured: portfolio.is_featured ?? false,
        _method: 'put',
    });

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

    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('portfolios.update', portfolio.id), {
            data: {
                ...data,
                remove_image: removeImage
            },
            onSuccess: () => {
                toast.fire({
                    icon: 'success',
                    title: 'Portfolio updated successfully.'
                });
            }
        });
    };

    return (
        <AdminLayout>
            <Head title="Edit Portfolio" />

            <div className="py-8 px-4 sm:px-6 lg:px-8">
                <div className="max-w-3xl mx-auto">
                    {/* Header Section */}
                    <div className="mb-8">
                        <div className="flex items-center mb-2">
                            <Link href={route('admin.portfolios.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 Portfolios
                            </Link>
                        </div>
                        <h1 className="text-2xl font-bold text-gray-900">Edit Portfolio</h1>
                        <p className="mt-1 text-sm text-gray-500">
                            Update the content and settings for this portfolio project.
                        </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">Project Information</h3>
                            <p className="mt-1 max-w-2xl text-sm text-gray-500">
                                Modify the content and settings for your portfolio project.
                            </p>
                        </div>
                        
                        <form onSubmit={submit} className="space-y-6 p-6">
                            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                                <div className="sm:col-span-1">
                                    <InputLabel htmlFor="title" value="Project Title" />
                                    <TextInput
                                        id="title"
                                        type="text"
                                        name="title"
                                        value={data.title}
                                        className="mt-1 block w-full"
                                        placeholder="e.g., E-commerce Website"
                                        isFocused={true}
                                        onChange={(e) => setData('title', e.target.value)}
                                    />
                                    <p className="mt-1 text-sm text-gray-500">A clear, descriptive name for your project</p>
                                    <InputError message={errors.title} className="mt-2" />
                                </div>

                                <div className="sm:col-span-1">
                                    <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)}
                                    />
                                    <p className="mt-1 text-sm text-gray-500">Lower numbers appear first</p>
                                    <InputError message={errors.order} className="mt-2" />
                                </div>
                            </div>

                            <div>
                                <InputLabel htmlFor="description" value="Project 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 your project in detail..."
                                    onChange={(e) => setData('description', e.target.value)}
                                ></textarea>
                                <p className="mt-1 text-sm text-gray-500">Provide a detailed description of the project, challenges, and solutions</p>
                                <InputError message={errors.description} className="mt-2" />
                            </div>

                            <div>
                                <InputLabel htmlFor="link" value="Project Link" />
                                <TextInput
                                    id="link"
                                    type="text"
                                    name="link"
                                    value={data.link}
                                    className="mt-1 block w-full"
                                    placeholder="https://example.com"
                                    onChange={(e) => setData('link', e.target.value)}
                                />
                                <p className="mt-1 text-sm text-gray-500">URL where users can view the live project</p>
                                <InputError message={errors.link} className="mt-2" />
                            </div>

                            <div>
                                <InputLabel htmlFor="image" value="Project Image" />
                                <div className="mt-1">
                                    {imagePreview ? (
                                        <div className="flex flex-col items-center">
                                            <img src={imagePreview} alt="Project 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>
                                <p className="mt-1 text-sm text-gray-500">Recommended dimensions: 1200x800 pixels</p>
                                <InputError message={errors.image} className="mt-2" />
                            </div>

                            <div className="flex items-center">
                                <input
                                    id="is_featured"
                                    name="is_featured"
                                    type="checkbox"
                                    checked={data.is_featured}
                                    onChange={(e) => setData('is_featured', e.target.checked)}
                                    className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                                />
                                <label htmlFor="is_featured" className="ml-2 block text-sm text-gray-900">
                                    Feature this project on the homepage
                                </label>
                            </div>

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

                    {/* Help Section */}
                    <div className="mt-8 bg-blue-50 overflow-hidden shadow rounded-lg">
                        <div className="px-4 py-5 sm:p-6">
                            <h3 className="text-lg leading-6 font-medium text-blue-800">Portfolio Guidelines</h3>
                            <div className="mt-2 max-w-xl text-sm text-blue-700">
                                <ul className="list-disc pl-5 space-y-1">
                                    <li>Use high-quality images that showcase your project effectively</li>
                                    <li>Write detailed descriptions that highlight your role and contributions</li>
                                    <li>Include links to live projects whenever possible</li>
                                    <li>Set appropriate order values to control project sequence</li>
                                    <li>Feature only your best work on the homepage</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}