/**
 * ダッシュボードページ
 *
 * システム状態チェック・フォント警告・統計情報を表示。
 */
import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import useCan from '../hooks/useCan';
import GuideSection from '../components/GuideSection';

function StatusIcon( { ok } ) {
	return <span style={ { color: ok ? '#00a32a' : '#d63638', marginRight: '8px' } }>{ ok ? '✓' : '✗' }</span>;
}

export default function Dashboard() {
	const [ status, setStatus ] = useState( null );
	const [ loading, setLoading ] = useState( true );
	const [ downloading, setDownloading ] = useState( false );
	const [ downloadResult, setDownloadResult ] = useState( null );
	const [ uploadingKey, setUploadingKey ] = useState( null );
	const [ uploadResult, setUploadResult ] = useState( null );
	const canManageSettings = useCan( 'conf_manager_manage_settings' );

	const fetchStatus = () => {
		// 管理者は完全なsystem-status、それ以外はdashboard-stats
		const endpoint = canManageSettings
			? '/conf-manager/v1/admin/system-status'
			: '/conf-manager/v1/admin/dashboard-stats';
		apiFetch( { path: endpoint } )
			.then( setStatus )
			.catch( () => {} )
			.finally( () => setLoading( false ) );
	};

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

	const handleFontDownload = () => {
		setDownloading( true );
		setDownloadResult( null );
		apiFetch( { path: '/conf-manager/v1/admin/fonts/download', method: 'POST' } )
			.then( ( res ) => {
				setDownloadResult( res );
				fetchStatus();
			} )
			.catch( () => {
				setDownloadResult( { success: false, message: __( 'Download failed.', 'conferencemanager' ) } );
			} )
			.finally( () => setDownloading( false ) );
	};

	const handleFontUpload = ( fontKey, fileObj ) => {
		if ( ! fileObj ) {
			return;
		}
		setUploadingKey( fontKey );
		setUploadResult( null );
		const formData = new FormData();
		formData.append( 'font', fontKey );
		formData.append( 'file', fileObj );
		apiFetch( { path: '/conf-manager/v1/admin/fonts/upload', method: 'POST', body: formData } )
			.then( ( res ) => {
				setUploadResult( res );
				if ( res && res.status ) {
					setStatus( ( prev ) => ( prev ? { ...prev, fonts: res.status } : prev ) );
				}
				fetchStatus();
			} )
			.catch( ( err ) => {
				setUploadResult( { success: false, message: ( err && err.message ) || __( 'Upload failed.', 'conferencemanager' ) } );
			} )
			.finally( () => setUploadingKey( null ) );
	};

	if ( loading ) {
		return (
			<div>
				<h2>{ __( 'Dashboard', 'conferencemanager' ) }</h2>
				<p>{ __( 'Loading...', 'conferencemanager' ) }</p>
			</div>
		);
	}

	if ( ! status ) {
		return (
			<div>
				<h2>{ __( 'Dashboard', 'conferencemanager' ) }</h2>
				<p>{ __( 'Failed to retrieve system status.', 'conferencemanager' ) }</p>
			</div>
		);
	}

	const ipaexMissing = status.fonts && ( ! status.fonts.ipaexg.exists || ! status.fonts.ipaexm.exists );

	return (
		<div>
			<h2>{ __( 'Dashboard', 'conferencemanager' ) }</h2>

			<GuideSection
				hero={ {
					title: __( 'Welcome to Conference Manager', 'conferencemanager' ),
					description: __( 'Manage academic conference registrations, payments, and document automation all in one place.', 'conferencemanager' ),
				} }
				cards={ [
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M12 20h9" /><path d="M16.5 3.5a2.121 2.121 0 013 3L7 19l-4 1 1-4L16.5 3.5z" /></svg>,
						title: __( 'Basic Workflow', 'conferencemanager' ),
						description: __( 'Create events → Accept registrations → Manage payments → Issue invoices and certificates.', 'conferencemanager' ),
						tips: [
							__( 'Start by creating a new event in Event Management', 'conferencemanager' ),
							__( 'Set fees per member type using the pricing matrix', 'conferencemanager' ),
							__( 'Set the registration start date and publish', 'conferencemanager' ),
						],
					},
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="11" width="18" height="11" rx="2" ry="2" /><path d="M7 11V7a5 5 0 0110 0v4" /></svg>,
						title: __( 'Security', 'conferencemanager' ),
						description: __( 'Personal data is encrypted with AES-256-GCM. Manage member data with confidence.', 'conferencemanager' ),
						tips: [
							__( 'Be sure to set the encryption key in Setup', 'conferencemanager' ),
							__( 'My Page uses OTP email verification for identity confirmation', 'conferencemanager' ),
							__( 'Operation logs record all administrator actions', 'conferencemanager' ),
							__( 'Compliant with the Anti-Spam Email Act', 'conferencemanager' ),
						],
					},
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="12" r="10" /><polyline points="12 6 12 12 16 14" /></svg>,
						title: __( 'Tips for Operations', 'conferencemanager' ),
						description: __( 'Best practices for smooth conference operations.', 'conferencemanager' ),
						tips: [
							__( 'Test with a trial registration before publishing the event', 'conferencemanager' ),
							__( 'Regularly confirm payments through payment management', 'conferencemanager' ),
							__( 'Certificates with QR codes streamline on-site check-in', 'conferencemanager' ),
						],
					},
				] }
			/>

			{ /* フォント警告（管理者のみ） */ }
			{ canManageSettings && ipaexMissing && (
				<div style={ {
					background: '#fff3cd',
					border: '1px solid #ffc107',
					borderLeft: '4px solid #ffc107',
					padding: '16px 20px',
					marginBottom: '20px',
					borderRadius: '4px',
				} }>
					<h3 style={ { margin: '0 0 8px', color: '#856404' } }>
						{ __( 'PDF fonts are not installed', 'conferencemanager' ) }
					</h3>
					<p style={ { margin: '0 0 12px', color: '#856404' } }>
						{ __( 'Japanese fonts (IPAex Gothic and IPAex Mincho) are required for generating invoice, receipt, and certificate PDFs.', 'conferencemanager' ) }
					</p>
					<button
						className="button button-primary"
						onClick={ handleFontDownload }
						disabled={ downloading }
						style={ { marginRight: '12px' } }
					>
						{ downloading
							? __( 'Downloading...', 'conferencemanager' )
							: __( 'Download IPAex Fonts', 'conferencemanager' ) }
					</button>
					<span style={ { fontSize: '12px', color: '#666' } }>
						{ __( 'Automatic download under IPA Font License', 'conferencemanager' ) }
					</span>

					{ downloadResult && (
						<div style={ {
							marginTop: '12px',
							padding: '10px 14px',
							borderRadius: '4px',
							background: downloadResult.success ? '#d4edda' : '#f8d7da',
							color: downloadResult.success ? '#155724' : '#721c24',
							fontSize: '13px',
						} }>
							{ downloadResult.success
								? __( 'Font download complete.', 'conferencemanager' )
								: ( downloadResult.message || __( 'Download failed. Please install manually.', 'conferencemanager' ) ) }
							{ downloadResult.fonts && ! downloadResult.success && (
								<ul style={ { margin: '8px 0 0', paddingLeft: '20px' } }>
									{ Object.entries( downloadResult.fonts ).map( ( [ key, val ] ) => (
										<li key={ key }>{ key }: { val.message }</li>
									) ) }
								</ul>
							) }
						</div>
					) }

					<div style={ { margin: '16px 0 0', paddingTop: '14px', borderTop: '1px solid #ffe08a' } }>
						<p style={ { margin: '0 0 8px', fontSize: '13px', fontWeight: 600, color: '#856404' } }>
							{ __( 'If automatic download is not available (manual upload)', 'conferencemanager' ) }
						</p>
						<p style={ { margin: '0 0 10px', fontSize: '12px', color: '#666' } }>
							{ __( 'You can upload the IPAex font .ttf files (ipaexg.ttf / ipaexm.ttf) directly from the form below. This also works on servers that cannot reach external sites.', 'conferencemanager' ) }
							{ ' ' }
							<a href="https://moji.or.jp/ipafont/ipafontdownload/" target="_blank" rel="noopener noreferrer">
								{ __( 'IPA official site', 'conferencemanager' ) }
							</a>
							{ __( 'It is also available here.', 'conferencemanager' ) }
						</p>
						{ [
							{ key: 'ipaexg', label: __( 'IPAex Gothic (ipaexg.ttf)', 'conferencemanager' ) },
							{ key: 'ipaexm', label: __( 'IPAex Mincho (ipaexm.ttf)', 'conferencemanager' ) },
						].map( ( f ) => {
							const installed = status.fonts && status.fonts[ f.key ] && status.fonts[ f.key ].exists;
							return (
								<div key={ f.key } style={ { display: 'flex', alignItems: 'center', gap: '8px', margin: '0 0 8px', flexWrap: 'wrap' } }>
									<StatusIcon ok={ installed } />
									<span style={ { fontSize: '13px', minWidth: '180px' } }>{ f.label }</span>
									<input
										type="file"
										accept=".ttf"
										disabled={ uploadingKey === f.key }
										onChange={ ( e ) => handleFontUpload( f.key, e.target.files && e.target.files[ 0 ] ) }
										style={ { fontSize: '12px' } }
									/>
									{ uploadingKey === f.key && (
										<span style={ { fontSize: '12px', color: '#666' } }>{ __( 'Uploading...', 'conferencemanager' ) }</span>
									) }
								</div>
							);
						} ) }
						{ uploadResult && (
							<div style={ {
								marginTop: '8px',
								padding: '8px 12px',
								borderRadius: '4px',
								background: uploadResult.success ? '#d4edda' : '#f8d7da',
								color: uploadResult.success ? '#155724' : '#721c24',
								fontSize: '13px',
							} }>
								{ uploadResult.message }
							</div>
						) }
					</div>
				</div>
			) }

			{ /* 承認待ち通知 */ }
			{ status.counts?.pending_approval > 0 && (
				<div style={ {
					background: '#fff3cd',
					border: '1px solid #ffc107',
					borderLeft: '4px solid #ffc107',
					padding: '12px 16px',
					marginBottom: '16px',
					borderRadius: '4px',
					display: 'flex',
					alignItems: 'center',
					gap: '12px',
				} }>
					<span style={ { fontSize: '24px' } }>{ status.counts.pending_approval }</span>
					<span style={ { color: '#856404' } }>
						{ __( ' self-registration(s) pending approval.', 'conferencemanager' ) }
						<a href="#/members" style={ { marginLeft: '8px' } }>{ __( 'Check in Member Management', 'conferencemanager' ) }</a>
					</span>
				</div>
			) }

			{ /* システム状態 */ }
			<div className="conf-manager-dashboard__grid">
				{ /* 環境チェック（管理者のみ） */ }
				{ canManageSettings && status.fonts && (
					<div className="conf-manager-dashboard__card">
						<h3>
							{ __( 'System Status', 'conferencemanager' ) }
						</h3>
						<ul style={ { listStyle: 'none', padding: 0, margin: 0 } }>
							<li><StatusIcon ok={ status.encryption?.key_set } /> { __( 'Encryption Key', 'conferencemanager' ) }</li>
							<li><StatusIcon ok={ status.pdf_available } /> { __( 'PDF Library (mPDF)', 'conferencemanager' ) }</li>
							<li><StatusIcon ok={ status.fonts.ipaexg.exists } /> IPAexゴシック (ipaexg.ttf)</li>
							<li><StatusIcon ok={ status.fonts.ipaexm.exists } /> IPAex明朝 (ipaexm.ttf)</li>
							<li><StatusIcon ok={ status.fonts.notosansjp.exists } /> Noto Sans JP</li>
							<li><StatusIcon ok={ status.stripe_configured } /> Stripe API</li>
						</ul>
					</div>
				) }

				{ /* 統計 */ }
				<div className="conf-manager-dashboard__card">
					<h3>
						{ __( 'Statistics', 'conferencemanager' ) }
					</h3>
					<dl style={ { display: 'grid', gridTemplateColumns: '120px 1fr', gap: '4px 12px', margin: 0 } }>
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Members', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0, fontSize: '20px', fontWeight: 'bold' } }>{ status.counts?.members ?? '—' }</dd>
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Events', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0, fontSize: '20px', fontWeight: 'bold' } }>{ status.counts?.events ?? '—' }</dd>
					</dl>
				</div>

				{ /* 決済サマリー */ }
				{ status.payment_stats && (
					<div className="conf-manager-dashboard__card">
						<h3>{ __( 'Payment Overview', 'conferencemanager' ) }</h3>
						<dl style={ { display: 'grid', gridTemplateColumns: '120px 1fr', gap: '4px 12px', margin: 0 } }>
							<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Paid', 'conferencemanager' ) }</dt>
							<dd style={ { margin: 0, fontSize: '18px', fontWeight: 'bold', color: '#00a32a' } }>
								¥{ Number( status.payment_stats.total_paid ).toLocaleString() }
								<span style={ { fontSize: '12px', color: '#757575', marginLeft: '4px' } }>({ status.payment_stats.paid_count }{ __( 'items', 'conferencemanager' ) })</span>
							</dd>
							<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Unpaid', 'conferencemanager' ) }</dt>
							<dd style={ { margin: 0, fontSize: '18px', fontWeight: 'bold', color: '#d63638' } }>
								¥{ Number( status.payment_stats.total_unpaid ).toLocaleString() }
								<span style={ { fontSize: '12px', color: '#757575', marginLeft: '4px' } }>({ status.payment_stats.unpaid_count }{ __( 'items', 'conferencemanager' ) })</span>
							</dd>
						</dl>
					</div>
				) }
			</div>

			{ /* イベント別参加者数 */ }
			{ status.event_stats && status.event_stats.length > 0 && (
				<div className="conf-manager-dashboard__card" style={ { marginTop: '16px' } }>
					<h3>{ __( 'Participants by Event', 'conferencemanager' ) }</h3>
					<table className="widefat striped" style={ { marginTop: '8px' } }>
						<thead>
							<tr>
								<th>{ __( 'Event', 'conferencemanager' ) }</th>
								<th>{ __( 'Event Date', 'conferencemanager' ) }</th>
								<th>{ __( 'Registrations', 'conferencemanager' ) }</th>
								<th>{ __( 'Paid', 'conferencemanager' ) }</th>
							</tr>
						</thead>
						<tbody>
							{ status.event_stats.map( ( ev ) => (
								<tr key={ ev.id }>
									<td><strong>{ ev.title }</strong></td>
									<td>{ ev.date_start ? ev.date_start.substring( 0, 10 ) : '—' }</td>
									<td>{ ev.total }</td>
									<td>{ ev.paid_count }</td>
								</tr>
							) ) }
						</tbody>
					</table>
				</div>
			) }
		</div>
	);
}
