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

export default function EditProperty({ isOpen, onClose, initialData }) {
    const [landlords, setLandlords] = useState([]);
    const [isSubmitting, setIsSubmitting] = useState(false);

    const { data, setData, put, processing, errors, transform } = useForm({
        title: '',
        description: '',
        address: '',
        latitude: '',
        longitude: '',
        property_type: '',
        bedrooms: '',
        bathrooms: '',
        size_sqm: '',
        monthly_rent: '',
        deposit_amount: '',
        is_furnished: false,
        status: 3,
        landlord_id: '',
        images: [],
        hostel: {
            university_nearby: '',
            distance_to_university: '',
            room_sharing: '',
            gender_restriction: '',
            meal_plan_available: false,
            study_room_available: false,
            curfew_time: '',
        },
    });
    
    // Transform data before submission - only include hostel if property type is Hostel
    transform((data) => {
        const transformed = { ...data };
        
        // Only include hostel data if property type is Hostel
        if (Number(data.property_type) !== 4) {
            delete transformed.hostel;
        } else 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') // Fetch landlords only
            .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');
            });
    }, []);

    // Update form data when initialData changes
    useEffect(() => {
        if (initialData) {
            setData({
                title: initialData.title || '',
                description: initialData.description || '',
                address: initialData.address || '',
                latitude: initialData.latitude || '',
                longitude: initialData.longitude || '',
                property_type: initialData.property_type || '',
                bedrooms: initialData.bedrooms || '',
                bathrooms: initialData.bathrooms || '',
                size_sqm: initialData.size_sqm || '',
                monthly_rent: initialData.monthly_rent || '',
                deposit_amount: initialData.deposit_amount || '',
                is_furnished: initialData.is_furnished || false,
                status: initialData.status || 3,
                landlord_id: initialData.landlord_id || '',
                images: initialData.images || [],
                hostel: initialData.hostel ? {
                    university_nearby: initialData.hostel.university_nearby || '',
                    distance_to_university: initialData.hostel.distance_to_university || '',
                    room_sharing: initialData.hostel.room_sharing ? Number(initialData.hostel.room_sharing) : '',
                    gender_restriction: initialData.hostel.gender_restriction ? Number(initialData.hostel.gender_restriction) : '',
                    meal_plan_available: initialData.hostel.meal_plan_available || false,
                    study_room_available: initialData.hostel.study_room_available || false,
                    curfew_time: initialData.hostel.curfew_time || '',
                } : {
                    university_nearby: '',
                    distance_to_university: '',
                    room_sharing: '',
                    gender_restriction: '',
                    meal_plan_available: false,
                    study_room_available: false,
                    curfew_time: '',
                },
            });
        }
    }, [initialData]);

    const propertyTypes = [
        { value: 1, label: 'House' },
        { value: 2, label: 'Apartment' },
        { value: 3, label: 'Room' },
        { value: 4, label: 'Hostel' },
        { value: 5, label: 'Office' }
    ];

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

    // Check if property type is Hostel
    const isHostel = Number(data.property_type) === 4;

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

    const handleImageSuccess = (filename) => {
        // Add the uploaded filename to images array
        const currentImages = Array.isArray(data.images) ? data.images : [];
        setData('images', [...currentImages, filename]);
        // Don't show toast here - FileUploadInput already shows it
    };

    const handleImageError = (error) => {
        // Don't show toast here - FileUploadInput already shows it
        console.error('Upload error:', error);
    };

    if (!isOpen) return null;

    return (
        <>
            <Toaster />
            <Modal
                isOpen={isOpen}
                onClose={onClose}
                title="Edit Property"
                primaryButtonText={processing || isSubmitting ? 'Updating...' : 'Update Property'}
                onPrimaryAction={handleSubmit}
                primaryButtonDisabled={processing || isSubmitting}
            >
                <form onSubmit={(e) => e.preventDefault()}>
                    <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="Property Type"
                                name="property_type"
                                value={data.property_type}
                                onChange={(e) => {
                                    const newType = e.target.value;
                                    setData('property_type', newType);
                                    // Clear hostel data if changing away from hostel
                                    if (Number(newType) !== 4) {
                                        setData('hostel', {
                                            university_nearby: '',
                                            distance_to_university: '',
                                            room_sharing: '',
                                            gender_restriction: '',
                                            meal_plan_available: false,
                                            study_room_available: false,
                                            curfew_time: '',
                                        });
                                    }
                                }}
                                options={propertyTypes}
                                error={errors.property_type}
                                required
                            />

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

                            {!isHostel && (
                                <div className="form-group">
                                    <div className="form-check">
                                        <input
                                            className="form-check-input"
                                            type="checkbox"
                                            id="is_furnished"
                                            checked={data.is_furnished}
                                            onChange={(e) => setData('is_furnished', e.target.checked)}
                                        />
                                        <label className="form-check-label" htmlFor="is_furnished">
                                            Furnished
                                        </label>
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Hostel-Specific Information - Only show when property type is Hostel */}
                        {isHostel && (
                            <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="editPropertyImageUpload"
                                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) => {
                                            // Handle both string paths (newly uploaded) and image objects (from database)
                                            let imageUrl;
                                            if (typeof img === 'string') {
                                                // Newly uploaded image (just the path)
                                                imageUrl = `/storage/${img}`;
                                            } else {
                                                // Image from database (has full_url or image_url)
                                                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>
                </form>
            </Modal>
        </>
    );
}
