import React, { useState, useEffect } from 'react';

export default function CustomFieldsManager() {
  const [customFields, setCustomFields] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadCustomFields();
  }, []);

  const loadCustomFields = async () => {
    setLoading(true);
    try {
      const result = await window.mcp.callTool('wrike_list_custom_fields', {});
      setCustomFields(result.customFields || []);
    } catch (error) {
      console.error('Failed to load custom fields:', error);
    } finally {
      setLoading(false);
    }
  };

  const getTypeColor = (type: string) => {
    const colors: Record<string, string> = {
      Text: '#3b82f6',
      DropDown: '#8b5cf6',
      Numeric: '#10b981',
      Currency: '#f59e0b',
      Date: '#ef4444',
      Checkbox: '#6b7280',
    };
    return colors[type] || '#6b7280';
  };

  return (
    <div style={{ background: '#111827', color: '#f3f4f6', minHeight: '100vh', padding: '24px' }}>
      <h1 style={{ fontSize: '24px', fontWeight: 'bold', marginBottom: '24px' }}>Custom Fields Manager</h1>
      
      <button
        onClick={loadCustomFields}
        style={{
          background: '#3b82f6',
          color: 'white',
          padding: '8px 16px',
          borderRadius: '6px',
          border: 'none',
          cursor: 'pointer',
          marginBottom: '24px',
        }}
      >
        Refresh
      </button>

      {loading ? (
        <div>Loading...</div>
      ) : (
        <div style={{ display: 'grid', gap: '12px' }}>
          {customFields.map(field => (
            <div
              key={field.id}
              style={{
                background: '#1f2937',
                padding: '16px',
                borderRadius: '8px',
                border: '1px solid #374151',
              }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '8px' }}>
                <h3 style={{ fontSize: '18px', fontWeight: '600' }}>{field.title}</h3>
                <span
                  style={{
                    padding: '4px 8px',
                    borderRadius: '4px',
                    background: getTypeColor(field.type) + '20',
                    color: getTypeColor(field.type),
                    fontSize: '14px',
                  }}
                >
                  {field.type}
                </span>
              </div>
              <div style={{ fontSize: '14px', color: '#9ca3af' }}>
                ID: {field.id}
              </div>
            </div>
          ))}
          {customFields.length === 0 && (
            <div style={{ textAlign: 'center', padding: '48px', color: '#6b7280' }}>
              No custom fields found
            </div>
          )}
        </div>
      )}
    </div>
  );
}
