const ContactInformationView = ({ currentUser, setCurrentUser }) => {
    const { useState, useEffect, useRef } = React;
    const [email, setEmail] = useState(currentUser.Email || '');
    const [phone, setPhone] = useState(currentUser.Phone || '');
    const [preferredContactMethods, setPreferredContactMethods] = useState(currentUser.PreferredContactMethods || ['email']);
    const [showSuccess, setShowSuccess] = useState(false);
    const [showError, setShowError] = useState(false);
    const [errorMessage, setErrorMessage] = useState('');
    const [isSaving, setIsSaving] = useState(false);
    const [attachments, setAttachments] = useState([]);
    const [isDragging, setIsDragging] = useState(false);
    const fileInputRef = useRef(null);

    console.log('ContactInformationView rendered with:', {
        email: currentUser.Email,
        phone: currentUser.Phone,
        preferredContactMethods: currentUser.PreferredContactMethods
    });

    // Helper to format 10-digit phone to display format
    const formatPhoneForDisplay = (digits) => {
        if (!digits) return '';
        const cleaned = digits.replace(/\D/g, '');
        if (cleaned.length !== 10) return digits; // Return as-is if not 10 digits
        return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6, 10)}`;
    };

    // Update local state when currentUser changes (from login or other updates)
    useEffect(() => {
        console.log('ContactInformationView useEffect triggered - updating local state');
        setEmail(currentUser.Email || '');
        setPhone(currentUser.Phone || '');
        setPreferredContactMethods(currentUser.PreferredContactMethods || ['email']);
    }, [currentUser.Email, currentUser.Phone, currentUser.PreferredContactMethods]);

    const formatPhoneNumber = (value) => {
        const digits = value.replace(/\D/g, '');
        if (digits.length === 0) return '';
        if (digits.length <= 3) return `(${digits}`;
        if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
        return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6, 10)}`;
    };

    const handlePhoneChange = (e) => {
        const formatted = formatPhoneNumber(e.target.value);
        setPhone(formatted);
    };

    const handleSave = async () => {
        // Strip phone formatting to get only digits (database expects 10 digits only)
        const phoneDigits = phone ? phone.replace(/\D/g, '') : null;

        // Validate phone has exactly 10 digits if provided
        if (!phoneDigits) {
            setErrorMessage('Phone number is required');
            setShowError(true);
            setTimeout(() => setShowError(false), 5000);
            return;
        }

        if (phoneDigits.length !== 10) {
            setErrorMessage('Phone number must be exactly 10 digits');
            setShowError(true);
            setTimeout(() => setShowError(false), 5000);
            return;
        }

        setIsSaving(true);
        setShowError(false);
        setShowSuccess(false);

        console.log('DEBUG: Saving phone number...');
        console.log('DEBUG: Username:', currentUser.Username);
        console.log('DEBUG: Phone (formatted):', phone);
        console.log('DEBUG: Phone (digits only):', phoneDigits);

        try {
            const requestBody = {
                username: currentUser.Username,
                phone: phoneDigits,  // Send only digits to database
                preferred_contact_methods: preferredContactMethods
            };
            console.log('DEBUG: Request body:', requestBody);

            const response = await fetch('/api/contact/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestBody)
            });

            console.log('DEBUG: Response status:', response.status);

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.detail || 'Failed to update contact information');
            }

            const data = await response.json();
            console.log('DEBUG: Response data:', data);

            // Format phone from database (10 digits) for display
            const formattedPhone = data.user.phone ? formatPhoneForDisplay(data.user.phone) : '';

            // Update currentUser in parent component
            setCurrentUser({
                ...currentUser,
                Email: data.user.email,
                Phone: formattedPhone,
                PreferredContactMethods: data.user.preferred_contact_methods || ['email']
            });

            // Update local state
            setEmail(data.user.email);
            setPhone(formattedPhone);
            setPreferredContactMethods(data.user.preferred_contact_methods || ['email']);

            console.log('DEBUG: Updated currentUser with:', data.user.email, formattedPhone, data.user.preferred_contact_methods);

            setShowSuccess(true);
            setTimeout(() => setShowSuccess(false), 5000);

        } catch (err) {
            setErrorMessage(err.message || 'Failed to update contact information. Please try again.');
            setShowError(true);
            setTimeout(() => setShowError(false), 5000);
        } finally {
            setIsSaving(false);
        }
    };

    const handleFileSelect = (e) => {
        const files = Array.from(e.target.files);
        const newAttachments = files.map(file => ({
            id: Date.now() + Math.random(),
            name: file.name,
            size: file.size
        }));
        setAttachments(prev => [...prev, ...newAttachments]);
    };

    const removeAttachment = (id) => {
        setAttachments(prev => prev.filter(att => att.id !== id));
    };

    const handleDragOver = (e) => {
        e.preventDefault();
        setIsDragging(true);
    };

    const handleDragLeave = (e) => {
        e.preventDefault();
        setIsDragging(false);
    };

    const handleDrop = (e) => {
        e.preventDefault();
        setIsDragging(false);
        const files = Array.from(e.dataTransfer.files);
        const newAttachments = files.map(file => ({
            id: Date.now() + Math.random(),
            name: file.name,
            size: file.size
        }));
        setAttachments(prev => [...prev, ...newAttachments]);
    };

    const formatFileSize = (bytes) => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    };

    return (
        <div className="h-full bg-gradient-to-br from-gray-50 to-primary/5 p-8 overflow-y-auto">
            <div className="max-w-4xl mx-auto space-y-6">
                {/* Header */}
                <div className="mb-8">
                    <h1 className="text-3xl font-bold text-gray-900 mb-2">My Profile</h1>
                    <p className="text-gray-600">Review your details and manage your contact preferences</p>
                </div>

                {/* Profile Card */}
                <div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                    {/* Profile Header with Gradient */}
                    <div className="bg-gradient-to-r from-primary to-primary-hover p-6">
                        <div className="flex items-center gap-4">
                            <div className="w-20 h-20 bg-white/20 backdrop-blur-sm rounded-full flex items-center justify-center border-4 border-white/30">
                                <span className="text-3xl font-bold text-white">
                                    {currentUser.FirstName?.[0]}{currentUser.LastName?.[0]}
                                </span>
                            </div>
                            <div className="flex-1">
                                <h2 className="text-2xl font-bold text-white">
                                    {currentUser.FirstName} {currentUser.LastName}
                                </h2>

                                {/* Username + Role pills */}
                                <div className="mt-2 flex flex-wrap items-center gap-2">
                                    {/* Username pill */}
                                    <div className="inline-flex items-center gap-2 px-3 py-1 bg-white/20 backdrop-blur-sm rounded-lg">
                                        <svg className="w-4 h-4 text-white/90" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                                strokeWidth={2}
                                                d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0z"
                                            />
                                        </svg>
                                        <span className="text-sm font-medium text-white/90">@{currentUser.Username}</span>
                                    </div>

                                    {/* Role pill */}
                                    <div className="inline-flex items-center gap-2 px-3 py-1 bg-white/20 backdrop-blur-sm rounded-lg">
                                        <svg className="w-4 h-4 text-white/90" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                                strokeWidth={2}
                                                d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
                                            />
                                        </svg>
                                        <span className="text-sm font-medium text-white/90">
                                            {currentUser.Role || "Not assigned"}
                                        </span>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>

                {/* Contact Information Card */}
                <div className="bg-white rounded-2xl shadow-sm border border-gray-200 p-6">
                    <div className="space-y-5">
                        {/* Email - Read Only */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                Email
                            </label>
                            <div className="relative">
                                <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                    </svg>
                                </div>
                                <input
                                    type="email"
                                    value={currentUser.Email}
                                    disabled
                                    className="w-full pl-12 pr-4 py-3.5 border-2 border-gray-200 rounded-xl bg-gray-50 text-gray-900 font-medium cursor-not-allowed"
                                />
                            </div>
                        </div>

                        {/* Phone Number */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                Phone
                            </label>
                            <div className="relative">
                                <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                    <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z" />
                                    </svg>
                                </div>
                                <input
                                    type="tel"
                                    value={phone}
                                    onChange={handlePhoneChange}
                                    disabled={isSaving}
                                    className="w-full pl-12 pr-4 py-3.5 border-2 border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary disabled:bg-gray-50 disabled:cursor-not-allowed transition-all text-gray-900 font-medium"
                                    placeholder="(555) 123-4567"
                                />
                            </div>
                        </div>

                        {/* Divider */}
                        <div className="border-t border-gray-200 my-6"></div>

                        {/* Contact Preferences */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-3">
                                Contact Preferences
                            </label>
                            <div className="space-y-3">
                                {/* Email Checkbox */}
                                <label className="flex items-center gap-3 p-3 border-2 border-gray-200 rounded-xl hover:border-primary/30 cursor-pointer transition-all group">
                                    <input
                                        type="checkbox"
                                        checked={preferredContactMethods.includes('email')}
                                        onChange={(e) => {
                                            if (e.target.checked) {
                                                setPreferredContactMethods([...preferredContactMethods, 'email']);
                                            } else {
                                                setPreferredContactMethods(preferredContactMethods.filter(m => m !== 'email'));
                                            }
                                        }}
                                        disabled={isSaving}
                                        style={{ accentColor: "#172C56" }}
                                        className="w-5 h-5 text-primary border-2 border-gray-300 rounded focus:ring-2 focus:ring-primary/20 disabled:opacity-50 disabled:cursor-not-allowed"
                                    />
                                    <div className="flex items-center gap-2 flex-1">
                                        <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                        </svg>
                                        <span className="font-medium text-gray-900">Email</span>
                                    </div>
                                </label>

                                {/* Phone Call Checkbox */}
                                <label className="flex items-center gap-3 p-3 border-2 border-gray-200 rounded-xl hover:border-primary/30 cursor-pointer transition-all group">
                                    <input
                                        type="checkbox"
                                        checked={preferredContactMethods.includes('call')}
                                        onChange={(e) => {
                                            if (e.target.checked) {
                                                setPreferredContactMethods([...preferredContactMethods, 'call']);
                                            } else {
                                                setPreferredContactMethods(preferredContactMethods.filter(m => m !== 'call'));
                                            }
                                        }}
                                        disabled={isSaving}
                                        style={{ accentColor: "#172C56" }}
                                        className="w-5 h-5 text-primary border-2 border-gray-300 rounded focus:ring-2 focus:ring-primary/20 disabled:opacity-50 disabled:cursor-not-allowed"
                                    />
                                    <div className="flex items-center gap-2 flex-1">
                                        <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                        </svg>
                                        <span className="font-medium text-gray-900">Phone Call</span>
                                    </div>
                                </label>

                                {/* Text Message Checkbox */}
                                <label className="flex items-center gap-3 p-3 border-2 border-gray-200 rounded-xl hover:border-primary/30 cursor-pointer transition-all group">
                                    <input
                                        type="checkbox"
                                        checked={preferredContactMethods.includes('text')}
                                        onChange={(e) => {
                                            if (e.target.checked) {
                                                setPreferredContactMethods([...preferredContactMethods, 'text']);
                                            } else {
                                                setPreferredContactMethods(preferredContactMethods.filter(m => m !== 'text'));
                                            }
                                        }}
                                        disabled={isSaving}
                                        style={{ accentColor: "#172C56" }}
                                        className="w-5 h-5 text-primary border-2 border-gray-300 rounded focus:ring-2 focus:ring-primary/20 disabled:opacity-50 disabled:cursor-not-allowed"
                                    />
                                    <div className="flex items-center gap-2 flex-1">
                                        <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
                                        </svg>
                                        <span className="font-medium text-gray-900">Text Message</span>
                                    </div>
                                </label>
                            </div>
                        </div>

                        {/* Alerts */}
                        {showError && (
                            <div className="bg-red-50 border-2 border-red-200 rounded-xl p-4 animate-in slide-in-from-top">
                                <div className="flex items-start gap-3">
                                    <div className="w-5 h-5 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                                        <svg className="w-3 h-3 text-red-600" fill="currentColor" viewBox="0 0 20 20">
                                            <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                                        </svg>
                                    </div>
                                    <div className="flex-1">
                                        <p className="text-sm font-semibold text-red-900">Update Failed</p>
                                        <p className="text-sm text-red-700 mt-1">{errorMessage}</p>
                                    </div>
                                </div>
                            </div>
                        )}

                        {showSuccess && (
                            <div className="bg-primary/5 border-2 border-primary/20 rounded-xl p-4 animate-in slide-in-from-top">
                                <div className="flex items-start gap-3">
                                    <div className="w-5 h-5 bg-primary/20 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                                        <svg className="w-3 h-3 text-primary" fill="currentColor" viewBox="0 0 20 20">
                                            <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                                        </svg>
                                    </div>
                                    <div className="flex-1">
                                        <p className="text-sm font-semibold text-primary">Success!</p>
                                        <p className="text-sm text-primary mt-1">Your contact information has been updated</p>
                                    </div>
                                </div>
                            </div>
                        )}

                        {/* Action Buttons */}
                        <div className="flex gap-3 pt-2">
                            <button
                                onClick={handleSave}
                                disabled={isSaving}
                                className="flex-1 px-6 py-3.5 bg-primary hover:bg-primary-hover text-white rounded-xl font-semibold transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 shadow-sm hover:shadow-md"
                            >
                                {isSaving ? (
                                    <>
                                        <svg className="animate-spin h-5 w-5" fill="none" viewBox="0 0 24 24">
                                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                        </svg>
                                        Saving...
                                    </>
                                ) : (
                                    <>
                                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                        </svg>
                                        Save Changes
                                    </>
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

// ═══════════════════════════════════════════════════════════════════════════
// VENDORS VIEW COMPONENT
// ═══════════════════════════════════════════════════════════════════════════