import { useState, useEffect } from 'react';
import { useForm, router } from '@inertiajs/react';
import { toast, Toaster } from 'react-hot-toast';
import InputField from '@/Components/Admin/ui/InputField';
import SelectField from '@/Components/Admin/ui/SelectField';
import FileUploadInput from '@/Components/Admin/ui/FileUploadInput';

export default function EditHostel({ hostel, property }) {
    const [landlords, setLandlords] = useState([]);
    const [isSubmitting, setIsSubmitting] = useState(false);

    const { data, setData, put, processing, errors, transform } = useForm({
        title: property?.title || '',
        description: property?.description || '',
        address: property?.address || '',
        latitude: property?.latitude || '',
        longitude: property?.longitude || '',
        property_type: property?.property_type || 4, // Always 4 for hostel
        bedrooms: property?.bedrooms || '',
        bathrooms: property?.bathrooms || '',
        size_sqm: property?.size_sqm || '',
        monthly_rent: property?.monthly_rent || '',
        deposit_amount: property?.deposit_amount || '',
        is_furnished: property?.is_furnished || false,
        status: property?.status || 3,
        landlord_id: property?.landlord_id || '',
        images: property?.images || [],
        hostel: {
            university_nearby: property?.hostel?.university_nearby || '',
            distance_to_university: property?.hostel?.distance_to_university || '',
            room_sharing: property?.hostel?.room_sharing || '',
            gender_restriction: property?.hostel?.gender_restriction || '',
            meal_plan_available: property?.hostel?.meal_plan_available || false,
            study_room_available: property?.hostel?.study_room_available || false,
            curfew_time: property?.hostel?.curfew_time || '',
        },
    });
    
    // Transform data before submission
    transform((data) => {
        const transformed = { ...data };
        
        // Always include hostel data for hostels
        if (transformed.hostel) {
            // Clean up hostel data
            if (transformed.hostel.curfew_time === '') {
                transformed.hostel.curfew_time = null;
            }
            if (transformed.hostel.distance_to_university === '') {
                transformed.hostel.distance_to_university = 0;
            }
            transformed.hostel.meal_plan_available = Boolean(transformed.hostel.meal_plan_available);
            transformed.hostel.study_room_available = Boolean(transformed.hostel.study_room_available);
        }
        
        return transformed;
    });

    // Fetch landlords for dropdown
    useEffect(() => {
        fetch('/admin/properties/landlords')
            .then(response => response.json())
            .then(data => {
                if (data.users) {
                    setLandlords(data.users);
                }
            })
            .catch(error => {
                console.error('Error fetching landlords:', error);
                toast.error('Failed to load landlords');
            });
    }, []);

    const statusOptions = [
        { value: 1, label: 'Available' },
        { value: 2, label: 'Occupied' },
        { value: 3, label: 'Pending' },
        { value: 4, label: 'Maintenance' }
    ];

    const roomSharingOptions = [
        { value: 1, label: 'Single' },
        { value: 2, label: 'Double' },
        { value: 3, label: 'Triple' }
    ];

    const genderRestrictionOptions = [
        { value: 1, label: 'Male' },
        { value: 2, label: 'Female' },
        { value: 3, label: 'Mixed' }
    ];

    const handleSubmit = (e) => {
        e.preventDefault();
        setIsSubmitting(true);
        
        put(`/admin/properties/${property.id}`, {
            onSuccess: (page) => {
                toast.success('Hostel property updated successfully!');
                setIsSubmitting(false);
                router.visit('/admin/hostels');
            },
            onError: (errors) => {
                const errorMessage = errors?.message || 'Failed to update hostel property';
                toast.error(errorMessage);
                setIsSubmitting(false);
            }
        });
    };

    const handleImageSuccess = (filename) => {
        const currentImages = Array.isArray(data.images) ? data.images : [];
        setData('images', [...currentImages, filename]);
    };

    const handleImageError = (error) => {
        console.error('Upload error:', error);
    };

    return (
        <>
            <Toaster />
            <div className="container-fluid">
                <div className="row">
                    <div className="col-12">
                        <div className="card">
                            <div className="card-header">
                                <h4 className="card-title">Edit Hostel Property</h4>
                            </div>
                            <div className="card-body">
                                <form onSubmit={handleSubmit}>
                                    <div className="row">
                                        {/* Basic Information */}
                                        <div className="col-lg-6">
                                            <h5>Basic Information</h5>
                                            <InputField
                                                label="Property Title"
                                                name="title"
                                                value={data.title}
                                                onChange={(e) => setData('title', e.target.value)}
                                                error={errors.title}
                                                required
                                            />
                                            
                                            <div className="form-group">
                                                <label>Description</label>
                                                <textarea
                                                    className={`form-control ${errors.description ? 'is-invalid' : ''}`}
                                                    name="description"
                                                    value={data.description}
                                                    onChange={(e) => setData('description', e.target.value)}
                                                    rows="3"
                                                    required
                                                />
                                                {errors.description && (
                                                    <div className="invalid-feedback">{errors.description}</div>
                                                )}
                                            </div>

                                            <SelectField
                                                label="Status"
                                                name="status"
                                                value={data.status}
                                                onChange={(e) => setData('status', e.target.value)}
                                                options={statusOptions}
                                                error={errors.status}
                                                required
                                            />
                                        </div>

                                        {/* Location Information */}
                                        <div className="col-lg-6">
                                            <h5>Location Information</h5>
                                            <InputField
                                                label="Address"
                                                name="address"
                                                value={data.address}
                                                onChange={(e) => setData('address', e.target.value)}
                                                error={errors.address}
                                                required
                                            />

                                            <div className="row">
                                                <div className="col-md-6">
                                                    <InputField
                                                        label="Latitude"
                                                        name="latitude"
                                                        type="number"
                                                        step="any"
                                                        value={data.latitude}
                                                        onChange={(e) => setData('latitude', e.target.value)}
                                                        error={errors.latitude}
                                                    />
                                                </div>
                                                <div className="col-md-6">
                                                    <InputField
                                                        label="Longitude"
                                                        name="longitude"
                                                        type="number"
                                                        step="any"
                                                        value={data.longitude}
                                                        onChange={(e) => setData('longitude', e.target.value)}
                                                        error={errors.longitude}
                                                    />
                                                </div>
                                            </div>
                                        </div>

                                        {/* Property Details */}
                                        <div className="col-lg-6">
                                            <h5>Property Details</h5>
                                            <div className="row">
                                                <div className="col-md-4">
                                                    <InputField
                                                        label="Bedrooms"
                                                        name="bedrooms"
                                                        type="number"
                                                        min="0"
                                                        max="20"
                                                        value={data.bedrooms}
                                                        onChange={(e) => setData('bedrooms', e.target.value)}
                                                        error={errors.bedrooms}
                                                    />
                                                </div>
                                                <div className="col-md-4">
                                                    <InputField
                                                        label="Bathrooms"
                                                        name="bathrooms"
                                                        type="number"
                                                        min="0"
                                                        max="20"
                                                        value={data.bathrooms}
                                                        onChange={(e) => setData('bathrooms', e.target.value)}
                                                        error={errors.bathrooms}
                                                    />
                                                </div>
                                                <div className="col-md-4">
                                                    <InputField
                                                        label="Size (sqm)"
                                                        name="size_sqm"
                                                        type="number"
                                                        min="0"
                                                        value={data.size_sqm}
                                                        onChange={(e) => setData('size_sqm', e.target.value)}
                                                        error={errors.size_sqm}
                                                    />
                                                </div>
                                            </div>

                                            <div className="row">
                                                <div className="col-md-6">
                                                    <InputField
                                                        label="Monthly Rent ($)"
                                                        name="monthly_rent"
                                                        type="number"
                                                        min="0"
                                                        step="0.01"
                                                        value={data.monthly_rent}
                                                        onChange={(e) => setData('monthly_rent', e.target.value)}
                                                        error={errors.monthly_rent}
                                                        required
                                                    />
                                                </div>
                                                <div className="col-md-6">
                                                    <InputField
                                                        label="Deposit Amount ($)"
                                                        name="deposit_amount"
                                                        type="number"
                                                        min="0"
                                                        step="0.01"
                                                        value={data.deposit_amount}
                                                        onChange={(e) => setData('deposit_amount', e.target.value)}
                                                        error={errors.deposit_amount}
                                                        required
                                                    />
                                                </div>
                                            </div>
                                        </div>

                                        {/* Additional Information */}
                                        <div className="col-lg-6">
                                            <h5>Additional Information</h5>
                                            <SelectField
                                                label="Landlord"
                                                name="landlord_id"
                                                value={data.landlord_id}
                                                onChange={(e) => setData('landlord_id', e.target.value)}
                                                options={landlords}
                                                error={errors.landlord_id}
                                                required
                                            />
                                        </div>

                                        {/* Hostel-Specific Information */}
                                        <div className="col-lg-12">
                                            <h5 className="mt-3">Hostel Details</h5>
                                            <div className="row">
                                                <div className="col-lg-6">
                                                    <InputField
                                                        label="University Nearby"
                                                        name="hostel.university_nearby"
                                                        value={data.hostel?.university_nearby || ''}
                                                        onChange={(e) => setData('hostel', {
                                                            ...data.hostel,
                                                            university_nearby: e.target.value
                                                        })}
                                                        error={errors['hostel.university_nearby'] || errors['hostel']?.['university_nearby']}
                                                        required
                                                    />

                                                    <InputField
                                                        label="Distance to University (km)"
                                                        name="hostel.distance_to_university"
                                                        type="number"
                                                        step="0.01"
                                                        min="0"
                                                        value={data.hostel?.distance_to_university || ''}
                                                        onChange={(e) => setData('hostel', {
                                                            ...data.hostel,
                                                            distance_to_university: e.target.value ? parseFloat(e.target.value) : ''
                                                        })}
                                                        error={errors['hostel.distance_to_university'] || errors['hostel']?.['distance_to_university']}
                                                        required
                                                    />

                                                    <SelectField
                                                        label="Room Sharing"
                                                        name="hostel.room_sharing"
                                                        value={data.hostel?.room_sharing || ''}
                                                        onChange={(e) => setData('hostel', {
                                                            ...data.hostel,
                                                            room_sharing: e.target.value ? parseInt(e.target.value) : ''
                                                        })}
                                                        options={roomSharingOptions}
                                                        error={errors['hostel.room_sharing'] || errors['hostel']?.['room_sharing']}
                                                        required
                                                    />

                                                    <SelectField
                                                        label="Gender Restriction"
                                                        name="hostel.gender_restriction"
                                                        value={data.hostel?.gender_restriction || ''}
                                                        onChange={(e) => setData('hostel', {
                                                            ...data.hostel,
                                                            gender_restriction: e.target.value ? parseInt(e.target.value) : ''
                                                        })}
                                                        options={genderRestrictionOptions}
                                                        error={errors['hostel.gender_restriction'] || errors['hostel']?.['gender_restriction']}
                                                        required
                                                    />
                                                </div>

                                                <div className="col-lg-6">
                                                    <InputField
                                                        label="Curfew Time (HH:MM)"
                                                        name="hostel.curfew_time"
                                                        type="time"
                                                        value={data.hostel?.curfew_time || ''}
                                                        onChange={(e) => setData('hostel', {
                                                            ...data.hostel,
                                                            curfew_time: e.target.value
                                                        })}
                                                        error={errors['hostel.curfew_time'] || errors['hostel']?.['curfew_time']}
                                                    />

                                                    <div className="form-group">
                                                        <div className="form-check">
                                                            <input
                                                                className="form-check-input"
                                                                type="checkbox"
                                                                id="meal_plan_available"
                                                                checked={data.hostel?.meal_plan_available || false}
                                                                onChange={(e) => setData('hostel', {
                                                                    ...data.hostel,
                                                                    meal_plan_available: e.target.checked
                                                                })}
                                                            />
                                                            <label className="form-check-label" htmlFor="meal_plan_available">
                                                                Meal Plan Available
                                                            </label>
                                                        </div>
                                                    </div>

                                                    <div className="form-group">
                                                        <div className="form-check">
                                                            <input
                                                                className="form-check-input"
                                                                type="checkbox"
                                                                id="study_room_available"
                                                                checked={data.hostel?.study_room_available || false}
                                                                onChange={(e) => setData('hostel', {
                                                                    ...data.hostel,
                                                                    study_room_available: e.target.checked
                                                                })}
                                                            />
                                                            <label className="form-check-label" htmlFor="study_room_available">
                                                                Study Room Available
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Images Upload */}
                                        <div className="col-lg-12">
                                            <h5>Property Images</h5>
                                            <FileUploadInput
                                                label="Upload Property Image"
                                                inputId="editHostelImageUpload"
                                                buttonText="Choose image"
                                                uploadUrl="/admin/api/properties/upload_image"
                                                onSuccess={handleImageSuccess}
                                                onError={handleImageError}
                                            />
                                            <small className="form-text text-muted">
                                                Maximum 5MB per image. Supported formats: JPEG, PNG, JPG, GIF, WEBP
                                            </small>
                                            {data.images && data.images.length > 0 && (
                                                <div className="mt-3">
                                                    <strong>Uploaded Images ({data.images.length}):</strong>
                                                    <div className="row mt-2">
                                                        {data.images.map((img, idx) => {
                                                            let imageUrl;
                                                            if (typeof img === 'string') {
                                                                imageUrl = `/storage/${img}`;
                                                            } else {
                                                                imageUrl = img.full_url || (img.image_url?.startsWith('http') ? img.image_url : `/storage/${img.image_url}`);
                                                            }
                                                            
                                                            return (
                                                                <div key={idx} className="col-md-3 mb-3">
                                                                    <div className="card">
                                                                        <img 
                                                                            src={imageUrl}
                                                                            alt={`Property ${idx + 1}`}
                                                                            className="card-img-top"
                                                                            style={{ height: '150px', objectFit: 'cover' }}
                                                                            onError={(e) => {
                                                                                e.target.onerror = null;
                                                                                e.target.src = '/admins/assets/images/no-image.png';
                                                                            }}
                                                                        />
                                                                        <div className="card-body p-2">
                                                                            <button
                                                                                type="button"
                                                                                className="btn btn-sm btn-danger btn-block"
                                                                                onClick={() => {
                                                                                    const newImages = data.images.filter((_, i) => i !== idx);
                                                                                    setData('images', newImages);
                                                                                }}
                                                                            >
                                                                                Remove
                                                                            </button>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            );
                                                        })}
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    </div>

                                    <div className="form-group mt-4">
                                        <button
                                            type="submit"
                                            className="btn btn-primary"
                                            disabled={processing || isSubmitting}
                                        >
                                            {processing || isSubmitting ? 'Updating...' : 'Update Hostel Property'}
                                        </button>
                                        <button
                                            type="button"
                                            className="btn btn-secondary ml-2"
                                            onClick={() => router.visit('/admin/hostels')}
                                        >
                                            Cancel
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}
