import { __ } from '@wordpress/i18n';
import { useState, useEffect, useCallback, Fragment } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import useNotice from '../../shared/useNotice';

type Log = {
	time: number;
	date: string;
	level: string;
	component: string;
	message: string;
	request?: any;
	response?: any;
};

type LogViewerProps = {
	endpoint: string;
	refreshTrigger?: number;
};

export default function LogViewer( { endpoint, refreshTrigger = 0 }: LogViewerProps ) {
	const [ logs, setLogs ] = useState< Log[] >( [] );
	const [ loading, setLoading ] = useState( false );
	const [ expanded, setExpanded ] = useState< Record< number, boolean > >( {} );
	const { showNotice } = useNotice();

	const fetchLogs = useCallback( async () => {
		setLoading( true );
		try {
			const result = await apiFetch< { success: boolean; data: Log[] } >( {
				url: endpoint,
				method: 'GET',
			} );
			if ( result.success ) {
				setLogs( result.data );
			}
		} catch ( error: any ) {
			showNotice( 'error', error.message || 'Failed to fetch logs' );
		}
		setLoading( false );
	}, [ endpoint, showNotice ] );

	const clearLogs = useCallback( async () => {
		if ( ! window.confirm( __( 'Are you sure you want to clear these logs?', 'liana-with-growthstack' ) ) ) {
			return;
		}
		setLoading( true );
		try {
			const result = await apiFetch< { success: boolean; message: string } >( {
				url: endpoint,
				method: 'DELETE',
			} );
			if ( result.success ) {
				setLogs( [] );
				showNotice( 'success', result.message || __( 'Logs cleared.', 'liana-with-growthstack' ) );
			}
		} catch ( error: any ) {
			showNotice( 'error', error.message || 'Failed to clear logs' );
		}
		setLoading( false );
	}, [ endpoint, showNotice ] );

	useEffect( () => {
		fetchLogs();
	}, [ fetchLogs, refreshTrigger ] );

	const toggleExpand = ( index: number ) => {
		setExpanded( ( prev ) => ( {
			...prev,
			[ index ]: ! prev[ index ],
		} ) );
	};

	const formatDate = ( timestamp: number ) => {
		return new Date( timestamp * 1000 ).toLocaleString();
	};

	return (
		<div className="growthstack-debug-logs gs-box" style={{ marginTop: '40px' }}>
			<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #eee', paddingBottom: '10px' }}>
				<h3 style={{ margin: 0 }}>
					{ __( 'API Error Logs', 'liana-with-growthstack' ) }
				</h3>
				<div>
					<button
						type="button"
						className="button"
						onClick={ fetchLogs }
						disabled={ loading }
						style={{ marginRight: '10px' }}
					>
						{ loading ? __( 'Refreshing...', 'liana-with-growthstack' ) : __( 'Refresh Logs', 'liana-with-growthstack' ) }
					</button>
					<button
						type="button"
						className="button button-link-delete"
						onClick={ clearLogs }
						disabled={ loading || logs.length === 0 }
						style={{ color: '#d63638' }}
					>
						{ __( 'Clear Logs', 'liana-with-growthstack' ) }
					</button>
				</div>
			</div>

			{ logs.length === 0 ? (
				<p style={{ color: '#666' }}>{ __( 'Log is empty.', 'liana-with-growthstack' ) }</p>
			) : (
				<div className="gs-logs-container" style={{ maxHeight: '1000px', overflowY: 'auto' }}>
					<table style={{ width: '100%', textAlign: 'left', borderCollapse: 'collapse', fontSize: '13px' }}>
						<thead>
							<tr>
								<th style={{ padding: '10px', borderBottom: '2px solid #ddd' }}>{ __( 'Date', 'liana-with-growthstack' ) }</th>
								<th style={{ padding: '10px', borderBottom: '2px solid #ddd' }}>{ __( 'Level', 'liana-with-growthstack' ) }</th>
								<th style={{ padding: '10px', borderBottom: '2px solid #ddd' }}>{ __( 'Component', 'liana-with-growthstack' ) }</th>
								<th style={{ padding: '10px', borderBottom: '2px solid #ddd' }}>{ __( 'Message', 'liana-with-growthstack' ) }</th>
								<th style={{ padding: '10px', borderBottom: '2px solid #ddd' }}>{ __( 'Details', 'liana-with-growthstack' ) }</th>
							</tr>
						</thead>
						<tbody>
							{ logs.map( ( log, index ) => (
								<Fragment key={ index }>
									<tr style={{ borderBottom: '1px solid #eee' }}>
										<td style={{ padding: '10px', whiteSpace: 'nowrap' }}>{ formatDate( log.time ) }</td>
										<td style={{ padding: '10px', color: log.level === 'error' ? '#d63638' : '#2271b1', fontWeight: 600 }}>
											{ (log.level || 'INFO').toUpperCase() }
										</td>
										<td style={{ padding: '10px' }}>{ log.component || '-' }</td>
										<td style={{ padding: '10px' }}>{ log.message || '-' }</td>
										<td style={{ padding: '10px' }}>
											<button
												type="button"
												className="button button-small"
												onClick={() => toggleExpand(index)}
											>
												{ expanded[index] ? __( 'Hide', 'liana-with-growthstack' ) : __( 'View', 'liana-with-growthstack' ) }
											</button>
										</td>
									</tr>
									{ expanded[index] && (
										<tr style={{ background: '#fafafa' }}>
											<td colSpan={5} style={{ padding: '15px', maxWidth: '1px' }}>
												{ log.request && (
													<>
														<strong>{ __( 'Request:', 'liana-with-growthstack' ) }</strong>
														<pre style={{ background: '#23282d', color: '#d4d4d4', padding: '10px', overflowX: 'auto', fontSize: '12px', marginTop: '5px' }}>
															{ JSON.stringify( log.request, null, 2 ) }
														</pre>
													</>
												) }
												{ log.response && (
													<>
														<strong style={{ display: 'block', marginTop: '10px' }}>{ __( 'Response:', 'liana-with-growthstack' ) }</strong>
														<pre style={{ background: '#23282d', color: '#d4d4d4', padding: '10px', overflowX: 'auto', fontSize: '12px', marginTop: '5px' }}>
															{ JSON.stringify( log.response, null, 2 ) }
														</pre>
													</>
												) }
											</td>
										</tr>
									)}
								</Fragment>
							) ) }
						</tbody>
					</table>
				</div>
			) }
		</div>
	);
}
