import React, { useState, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import { ToggleControl } from '@wordpress/components';
import MultiSelect from '../MultiSelect';

const TableSettings = ({ formData, setFormData }) => {
    const [availableColumns, setAvailableColumns] = useState({});

    // Initialize available columns
    useEffect(() => {
        const columns = {
            // Core user fields
            username: __('Username', 'wpuf-pro'),
            first_name: __('First Name', 'wpuf-pro'),
            last_name: __('Last Name', 'wpuf-pro'),
            nickname: __('Nickname', 'wpuf-pro'),
            display_name: __('Display Name', 'wpuf-pro'),
            email: __('Email', 'wpuf-pro'),
            website: __('Website', 'wpuf-pro'),
            bio: __('Bio', 'wpuf-pro'),
            registered_date: __('Registration Date', 'wpuf-pro'),

            // User statistics
            posts_count: __('Posts Count', 'wpuf-pro'),
            comments_count: __('Comments Count', 'wpuf-pro'),

            // Common meta fields
            location: __('Location', 'wpuf-pro'),
            company: __('Company', 'wpuf-pro'),
            phone: __('Phone', 'wpuf-pro'),
            skills: __('Skills', 'wpuf-pro'),
            job_title: __('Job Title', 'wpuf-pro'),
            department: __('Department', 'wpuf-pro'),
            experience: __('Experience', 'wpuf-pro'),
            education: __('Education', 'wpuf-pro'),
            social_media: __('Social Media', 'wpuf-pro'),
        };

        // Add user meta keys if available
        const metaKeys = window.wpufUserDirectory?.metaKeys || [];
        if (Array.isArray(metaKeys) && metaKeys.length > 0) {
            metaKeys.forEach(metaKey => {
                // Skip if we already have a predefined label for this field
                if (!columns[metaKey]) {
                    // Format the meta key to be more readable
                    const label = metaKey.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
                    columns[metaKey] = label;
                }
            });
        }

        setAvailableColumns(columns);
    }, []);

    // Ensure table_columns is always an array
    const tableColumns = Array.isArray(formData.table_columns)
        ? formData.table_columns
        : ['username', 'email', 'display_name'];

    const handleTableColumnsChange = (columns) => {
        setFormData({ ...formData, table_columns: columns });
    };

    return (
        <div className="wpuf-space-y-6">
            {/* Avatar Settings Section */}
            <div className="wpuf-space-y-4">
                <h3 className="wpuf-text-lg wpuf-font-medium wpuf-text-gray-900">
                    {__('Avatar Settings', 'wpuf-pro')}
                </h3>

                {/* Show Avatar Toggle */}
                <div className="wpuf-space-y-2">
                    <ToggleControl
                        label={__('Show Avatar', 'wpuf-pro')}
                        help={__('Display user avatars in the first column of the table', 'wpuf-pro')}
                        checked={formData.show_avatar || false}
                        onChange={(value) => setFormData({ ...formData, show_avatar: value })}
                    />
                </div>

                {/* Conditional Avatar Settings */}
                {formData.show_avatar && (
                    <div className="wpuf-space-y-4 wpuf-ml-6">
                        {/* Avatar Size */}
                        <div className="wpuf-space-y-2">
                            <label className="wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-700">
                                {__('Avatar Size', 'wpuf-pro')}
                            </label>
                            <select
                                name="avatar_size"
                                value={formData.avatar_size || 'medium'}
                                onChange={(e) => setFormData({ ...formData, avatar_size: e.target.value })}
                                className="wpuf-block wpuf-w-full wpuf-rounded-md wpuf-border-gray-300 wpuf-shadow-sm focus:wpuf-border-emerald-500 focus:wpuf-ring-emerald-500 wpuf-sm:wpuf-text-sm"
                            >
                                <option value="small">{__('Small (32px)', 'wpuf-pro')}</option>
                                <option value="medium">{__('Medium (96px)', 'wpuf-pro')}</option>
                                <option value="large">{__('Large (150px)', 'wpuf-pro')}</option>
                                <option value="xlarge">{__('Extra Large (300px)', 'wpuf-pro')}</option>
                            </select>
                        </div>

                        {/* Avatar Shape */}
                        <div className="wpuf-space-y-2">
                            <label className="wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-700">
                                {__('Avatar Shape', 'wpuf-pro')}
                            </label>
                            <select
                                name="avatar_shape"
                                value={formData.avatar_shape || 'circle'}
                                onChange={(e) => setFormData({ ...formData, avatar_shape: e.target.value })}
                                className="wpuf-block wpuf-w-full wpuf-rounded-md wpuf-border-gray-300 wpuf-shadow-sm focus:wpuf-border-emerald-500 focus:wpuf-ring-emerald-500 wpuf-sm:wpuf-text-sm"
                            >
                                <option value="circle">{__('Circle', 'wpuf-pro')}</option>
                                <option value="squared">{__('Squared', 'wpuf-pro')}</option>
                                <option value="rounded">{__('Rounded', 'wpuf-pro')}</option>
                            </select>
                        </div>

                        {/* Fallback Type */}
                        <div className="wpuf-space-y-2">
                            <label className="wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-700">
                                {__('Fallback Type', 'wpuf-pro')}
                            </label>
                            <select
                                name="avatar_fallback_type"
                                value={formData.avatar_fallback_type || 'gravatar'}
                                onChange={(e) => setFormData({ ...formData, avatar_fallback_type: e.target.value })}
                                className="wpuf-block wpuf-w-full wpuf-rounded-md wpuf-border-gray-300 wpuf-shadow-sm focus:wpuf-border-emerald-500 focus:wpuf-ring-emerald-500 wpuf-sm:wpuf-text-sm"
                            >
                                <option value="initials">{__('Initials', 'wpuf-pro')}</option>
                                <option value="gravatar">{__('Gravatar', 'wpuf-pro')}</option>
                            </select>
                        </div>
                    </div>
                )}
            </div>

            {/* Column Configuration Section */}
            <div className="wpuf-space-y-4">
                <h3 className="wpuf-text-lg wpuf-font-medium wpuf-text-gray-900">
                    {__('Column Configuration', 'wpuf-pro')}
                </h3>

                <div className="wpuf-space-y-2">
                    <label className="wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-700">
                        {__('Table Columns', 'wpuf-pro')}
                    </label>

                    <MultiSelect
                        selectedLabel="columns"
                        options={availableColumns}
                        value={tableColumns}
                        onChange={handleTableColumnsChange}
                        placeholder={__('Select columns...', 'wpuf-pro')}
                        sortable={true}
                        searchable={true}
                    />
                </div>

                <div className="wpuf-text-xs wpuf-text-gray-500 wpuf-bg-gray-50 wpuf-p-3 wpuf-rounded-md">
                    <p className="wpuf-mb-2">
                        <strong>{__('Note:', 'wpuf-pro')}</strong> {__('Column order:', 'wpuf-pro')}
                    </p>
                    <ol className="wpuf-list-decimal wpuf-list-inside wpuf-space-y-1">
                        <li>{__('Avatar (if enabled)', 'wpuf-pro')}</li>
                        <li>{__('Selected columns (in order above)', 'wpuf-pro')}</li>
                        <li>{__('View Profile button', 'wpuf-pro')}</li>
                    </ol>
                </div>
            </div>
        </div>
    );
};

export default TableSettings;
