import { useState } from 'react';
import { IoIosRefresh, IoIosLink } from 'react-icons/io';
import { useLanguage } from '../../contexts/LanguageContext';
import sharedStyles from '../../components/PageManager/pages.module.css';
import styles from './HomeStyles/TestSharepoint.module.css'
import { TestSharepointTable, useTestSharepointLogic } from '../../components/TestSharepoint'
function TestSharepoint() {
const { t } = useLanguage();
const {
connections,
selectedConnection,
connectionLoading,
connectionError,
documents,
documentsLoading,
documentsError,
columns,
actions,
testingConnections,
connectionTestResults,
discoveredSites,
sitesDiscovered,
tokenDebugInfo,
handleSelectConnection,
handleTestConnection,
handleListDocuments,
handleDiscoverSites,
handleSelectSite,
handleDebugTokens,
handleCleanupTokens,
handleFolderNavigation,
refetchConnections
} = useTestSharepointLogic();
const [tableRefreshKey, setTableRefreshKey] = useState(0);
const [siteUrl, setSiteUrl] = useState('https://your-tenant.sharepoint.com/sites/your-site');
const [folderPaths, setFolderPaths] = useState(['/']);
const onTestConnection = async (connectionId: string) => {
await handleTestConnection(connectionId);
};
const onListDocuments = async () => {
console.log('onListDocuments called with:', { siteUrl, folderPaths });
await handleListDocuments(siteUrl, folderPaths);
// Force table refresh to show new data
const newKey = tableRefreshKey + 1;
console.log('Setting tableRefreshKey to:', newKey);
setTableRefreshKey(newKey);
};
const onDiscoverSites = async () => {
await handleDiscoverSites();
};
const onSelectSite = (selectedSiteUrl: string) => {
setSiteUrl(selectedSiteUrl);
handleSelectSite(selectedSiteUrl);
};
const onRowClick = (row: any) => {
console.log('Row clicked:', row);
if (row.type === 'folder') {
const currentPath = folderPaths[0] || '/';
const newPath = handleFolderNavigation(row, currentPath);
console.log('Navigating from', currentPath, 'to', newPath);
setFolderPaths([newPath]);
// Automatically refresh the document list with the new path
handleListDocuments(siteUrl, [newPath]);
setTableRefreshKey(prev => prev + 1);
}
};
const renderConnectionCard = (connection: any) => {
const testResult = connectionTestResults[connection.id];
const isTestingThis = testingConnections.has(connection.id);
return (
handleSelectConnection(connection.id)}
>
{connection.externalUsername || connection.id}
{connection.status}
{connection.externalEmail && (
{connection.externalEmail}
)}
{testResult && (
{testResult.success ? '✓' : '✗'}
)}
);
};
return (
{t('sharepoint.title')}
{/* Connections Section */}
{t('sharepoint.connections.title')} ({connections.length})
{connectionError && (
{connectionError}
)}
{connections.length === 0 ? (
{connectionLoading ?
t('sharepoint.connections.loading') :
t('sharepoint.connections.noConnections')
}
) : (
{connections.map(renderConnectionCard)}
)}
{/* Token Debug Section */}
{tokenDebugInfo && (
<>
🔍 Token Debug Information
User ID: {tokenDebugInfo.data?.userId || 'Unknown'}
All Tokens Count: {tokenDebugInfo.data?.allTokensCount || 0}
{tokenDebugInfo.data?.allTokens && tokenDebugInfo.data.allTokens.length > 0 && (
Microsoft Tokens:
{tokenDebugInfo.data.allTokens.map((token: any, index: number) => (
Token ID: {token.id}
Authority: {token.authority}
Expires At: {new Date(token.expiresAt * 1000).toLocaleString()}
Is Expired: {token.isExpired ? '❌ YES' : '✅ NO'}
Has Access Token: {token.hasAccessToken ? '✅ YES' : '❌ NO'}
Has Refresh Token: {token.hasRefreshToken ? '✅ YES' : '❌ NO'}
))}
)}
{tokenDebugInfo.data?.sharepointMethodToken && (
SharePoint Method Token Status:
{tokenDebugInfo.data.sharepointMethodToken.tokenFound ? (
✅ Token Found
Token ID: {tokenDebugInfo.data.sharepointMethodToken.tokenId}
Expires At: {new Date(tokenDebugInfo.data.sharepointMethodToken.expiresAt * 1000).toLocaleString()}
Is Expired: {tokenDebugInfo.data.sharepointMethodToken.isExpired ? '❌ YES' : '✅ NO'}
) : (
❌ No Token Found: {tokenDebugInfo.data.sharepointMethodToken.reason || tokenDebugInfo.data.sharepointMethodToken.error}
)}
)}
{/* Provide action recommendations */}
💡 Recommendation:
{tokenDebugInfo.data?.allTokens?.some((token: any) => token.isExpired) ? (
🔄
Your tokens are stale! The tokens weren't properly cleared. Use the button below to force cleanup:
After cleanup: Go to Connections page → Reconnect Microsoft account
) : !tokenDebugInfo.data?.allTokens?.some((token: any) => token.hasAccessToken) ? (
⚠️ No valid access tokens found. Please reconnect your Microsoft account in the Connections page.
) : (
✅ Tokens look valid. The issue might be with SharePoint permissions or scopes.
)}
>
)}
{/* SharePoint Configuration Section */}
{selectedConnection && (
<>
SharePoint Configuration
setSiteUrl(e.target.value)}
placeholder="https://your-tenant.sharepoint.com/sites/your-site"
style={{ flex: 1 }}
/>
{sitesDiscovered && discoveredSites.length > 0 && (
{discoveredSites.map((site, index) => (
onSelectSite(site.url)}
>
{site.name}
({site.type})
{site.url}
{site.description && (
{site.description}
)}
))}
)}
{sitesDiscovered && discoveredSites.length === 0 && (
{t('sharepoint.sites.noSites')}
{documentsError && (
Technical details: {documentsError}
{documentsError.includes('401') || documentsError.includes('InvalidAuthenticationToken') ? (
⚠️ {t('sharepoint.sites.authError')}
{t('sharepoint.sites.retryConnection')}
) : (
Please check your Microsoft connection and permissions.
)}
)}
)}
>
)}
{/* Documents Table Section */}
{/* Breadcrumb Navigation */}
Current Path:
{folderPaths[0] === '/' ? (
📁 Root
) : (
<>
{
setFolderPaths(['/']);
handleListDocuments(siteUrl, ['/']);
setTableRefreshKey(prev => prev + 1);
}}
>
📁 Root
{folderPaths[0].split('/').filter(Boolean).map((part, index, array) => {
const pathToHere = '/' + array.slice(0, index + 1).join('/');
const isLast = index === array.length - 1;
return (
/
{
setFolderPaths([pathToHere]);
handleListDocuments(siteUrl, [pathToHere]);
setTableRefreshKey(prev => prev + 1);
} : undefined}
>
📁 {part}
);
})}
>
)}
);
}
export default TestSharepoint;