/**
 * 決済管理ページ
 *
 * 決済一覧・入金消込・返金・売上集計・CSVエクスポート。
 */
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
	Button,
	TextControl,
	SelectControl,
	Modal,
	Notice,
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import DataTable from '../components/DataTable';
import useCan from '../hooks/useCan';
import GuideSection from '../components/GuideSection';

const METHOD_LABELS = {
	bank: __( 'Bank Transfer', 'conferencemanager' ),
	stripe: 'Stripe',
};

const STATUS_LABELS = {
	pending: __( 'Unpaid', 'conferencemanager' ),
	completed: __( 'Paid', 'conferencemanager' ),
	refunded: __( 'Refunded', 'conferencemanager' ),
	partial_refund: __( 'Partial Refund', 'conferencemanager' ),
	failed: __( 'Failed', 'conferencemanager' ),
};

const STATUS_COLORS = {
	pending: '#d63638',
	completed: '#00a32a',
	refunded: '#757575',
	partial_refund: '#dba617',
	failed: '#b32d2e',
};

export default function Payments() {
	const [ items, setItems ] = useState( [] );
	const [ total, setTotal ] = useState( 0 );
	const [ page, setPage ] = useState( 1 );
	const [ statusFilter, setStatusFilter ] = useState( '' );
	const [ methodFilter, setMethodFilter ] = useState( '' );
	const [ eventFilter, setEventFilter ] = useState( '' );
	const [ loading, setLoading ] = useState( false );
	const [ notice, setNotice ] = useState( null );

	// イベント一覧
	const [ events, setEvents ] = useState( [] );

	// 売上集計
	const [ summary, setSummary ] = useState( null );

	// 入金確認モーダル
	const [ confirmModal, setConfirmModal ] = useState( null );
	const [ confirmName, setConfirmName ] = useState( '' );
	const [ confirmDate, setConfirmDate ] = useState( '' );

	// 返金モーダル
	const [ refundModal, setRefundModal ] = useState( null );
	const [ refundType, setRefundType ] = useState( 'full' );
	const [ refundAmount, setRefundAmount ] = useState( '' );
	const [ refundReason, setRefundReason ] = useState( '' );
	const [ refunding, setRefunding ] = useState( false );

	// 詳細モーダル
	const [ detailModal, setDetailModal ] = useState( null );

	// イベント一覧取得
	useEffect( () => {
		apiFetch( { path: '/conf-manager/v1/events?per_page=100' } )
			.then( ( data ) => {
				const list = Array.isArray( data ) ? data : data.items || [];
				setEvents( list );
			} )
			.catch( () => {} );
	}, [] );

	// 売上集計取得
	useEffect( () => {
		if ( ! eventFilter ) {
			setSummary( null );
			return;
		}
		apiFetch( { path: `/conf-manager/v1/payments/summary/${ eventFilter }` } )
			.then( setSummary )
			.catch( () => setSummary( null ) );
	}, [ eventFilter ] );

	const fetchItems = useCallback( async () => {
		setLoading( true );
		try {
			const params = new URLSearchParams( { page, per_page: 20 } );
			if ( statusFilter ) params.set( 'status', statusFilter );
			if ( methodFilter ) params.set( 'method', methodFilter );
			if ( eventFilter ) params.set( 'event_id', eventFilter );

			const response = await apiFetch( {
				path: `/conf-manager/v1/payments?${ params }`,
				parse: false,
			} );
			const data = await response.json();
			setItems( data );
			setTotal( parseInt( response.headers.get( 'X-WP-Total' ) || '0' ) );
		} catch ( err ) {
			setNotice( { status: 'error', message: err.message } );
		} finally {
			setLoading( false );
		}
	}, [ page, statusFilter, methodFilter, eventFilter ] );

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

	const openConfirm = ( payment ) => {
		setConfirmModal( payment );
		setConfirmName( payment.bank_transfer_name || '' );
		setConfirmDate( '' );
	};

	const handleConfirm = async () => {
		try {
			await apiFetch( {
				path: `/conf-manager/v1/payments/${ confirmModal.id }/confirm`,
				method: 'POST',
				data: {
					bank_transfer_name: confirmName,
					bank_transfer_date: confirmDate,
				},
			} );
			setNotice( { status: 'success', message: __( 'Payment confirmed.', 'conferencemanager' ) } );
			setConfirmModal( null );
			fetchItems();
		} catch ( err ) {
			setNotice( { status: 'error', message: err.message } );
		}
	};

	const openRefund = ( payment ) => {
		setRefundModal( payment );
		setRefundType( 'full' );
		setRefundAmount( '' );
		setRefundReason( '' );
	};

	const handleRefund = async () => {
		if ( ! window.confirm( __( 'Process refund? This action cannot be undone.', 'conferencemanager' ) ) ) {
			return;
		}
		setRefunding( true );
		try {
			const amount = refundType === 'partial' ? parseInt( refundAmount ) || 0 : 0;
			const res = await apiFetch( {
				path: `/conf-manager/v1/payments/${ refundModal.id }/refund`,
				method: 'POST',
				data: { amount, reason: refundReason },
			} );
			setNotice( { status: 'success', message: res.message } );
			setRefundModal( null );
			fetchItems();
		} catch ( err ) {
			setNotice( { status: 'error', message: err.message } );
		} finally {
			setRefunding( false );
		}
	};

	const handleExportCsv = async () => {
		if ( ! eventFilter ) return;
		try {
			const response = await apiFetch( {
				path: `/conf-manager/v1/payments/export/${ eventFilter }`,
				parse: false,
			} );
			const blob = await response.blob();
			const url = URL.createObjectURL( blob );
			const a = document.createElement( 'a' );
			a.href = url;
			a.download = response.headers.get( 'Content-Disposition' )?.match( /filename="(.+)"/ )?.[ 1 ] || 'payments.csv';
			document.body.appendChild( a );
			a.click();
			document.body.removeChild( a );
			URL.revokeObjectURL( url );
		} catch ( err ) {
			setNotice( { status: 'error', message: err.message } );
		}
	};

	const canEdit = useCan( 'conf_manager_edit_payments' );
	const canExport = useCan( 'conf_manager_export_payments' );

	const COLUMNS = [
		{ key: 'id', label: 'ID' },
		{ key: 'registration_id', label: __( 'Registration ID', 'conferencemanager' ) },
		{ key: 'member_name', label: __( 'Name', 'conferencemanager' ) },
		{ key: 'method', label: __( 'Payment Method', 'conferencemanager' ),
			render: ( val ) => METHOD_LABELS[ val ] || val,
		},
		{ key: 'amount', label: __( 'Amount', 'conferencemanager' ),
			render: ( val, row ) => `¥${ ( Number( val ) + Number( row.tax || 0 ) ).toLocaleString() }`,
		},
		{ key: 'status', label: __( 'Status', 'conferencemanager' ),
			render: ( val ) => {
				const color = STATUS_COLORS[ val ] || 'inherit';
				const label = STATUS_LABELS[ val ] || val;
				return (
					<span style={ { color, fontWeight: 'bold' } }>
						{ label }
					</span>
				);
			},
		},
		{ key: 'bank_transfer_name', label: __( 'Transfer Name', 'conferencemanager' ) },
		{ key: 'paid_at', label: __( 'Payment Date', 'conferencemanager' ),
			render: ( val ) => val ? val.substring( 0, 10 ) : '',
		},
		{
			key: 'actions',
			label: __( 'Actions', 'conferencemanager' ),
			render: ( _, row ) => (
				<div style={ { display: 'flex', gap: '4px' } }>
					<Button variant="tertiary" isSmall onClick={ () => setDetailModal( row ) }>
						{ __( 'Details', 'conferencemanager' ) }
					</Button>
					{ canEdit && row.status === 'pending' && (
						<Button variant="primary" isSmall onClick={ () => openConfirm( row ) }>
							{ __( 'Confirm Payment', 'conferencemanager' ) }
						</Button>
					) }
					{ canEdit && row.status === 'completed' && (
						<Button variant="secondary" isSmall isDestructive onClick={ () => openRefund( row ) }>
							{ __( 'Refund', 'conferencemanager' ) }
						</Button>
					) }
				</div>
			),
		},
	];

	return (
		<div>
			<div className="conf-manager-page-header">
				<h2>{ __( 'Payments', 'conferencemanager' ) }</h2>
				{ canExport && eventFilter && (
					<Button variant="secondary" onClick={ handleExportCsv }>
						{ __( 'CSV Export', 'conferencemanager' ) }
					</Button>
				) }
			</div>

			<GuideSection
				hero={ {
					title: __( 'Streamline Payment Management', 'conferencemanager' ),
					description: __( 'Manage the entire payment flow — from bank transfer reconciliation to Stripe payments and invoice issuance.', 'conferencemanager' ),
				} }
				cards={ [
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><polyline points="9 11 12 14 22 4" /><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11" /></svg>,
						title: __( 'Payment Confirmation & Reconciliation', 'conferencemanager' ),
						description: __( 'Confirm bank transfer payments and update participant status.', 'conferencemanager' ),
						tips: [
							__( 'Record transferor name and confirmation date for reconciliation', 'conferencemanager' ),
							__( 'Automatically notify participants after payment confirmation', 'conferencemanager' ),
							__( 'Filter by event and status', 'conferencemanager' ),
						],
					},
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" /><polyline points="14 2 14 8 20 8" /><line x1="16" y1="13" x2="8" y2="13" /><line x1="16" y1="17" x2="8" y2="17" /></svg>,
						title: __( 'Document Issuance', 'conferencemanager' ),
						description: __( 'Auto-generate invoices and receipts as PDFs, accessible from participants\' My Page.', 'conferencemanager' ),
						tips: [
							__( 'Invoices are auto-generated upon registration confirmation', 'conferencemanager' ),
							__( 'Receipts are available after payment confirmation', 'conferencemanager' ),
							__( 'Streamline accounting with CSV export', 'conferencemanager' ),
						],
					},
					{
						icon: <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="1.5"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18" /><polyline points="17 6 23 6 23 12" /></svg>,
						title: __( 'Refund Handling', 'conferencemanager' ),
						description: __( 'Supports full and partial refunds with reason tracking.', 'conferencemanager' ),
						tips: [
							__( 'Enter refund amount and reason to process', 'conferencemanager' ),
							__( 'Specify amount for partial refunds', 'conferencemanager' ),
							__( 'Refund history is available in payment details', 'conferencemanager' ),
						],
					},
				] }
			/>

			{ notice && (
				<Notice status={ notice.status } onDismiss={ () => setNotice( null ) }>
					{ notice.message }
				</Notice>
			) }

			{ /* 検索フィルタ */ }
			<form onSubmit={ ( e ) => { e.preventDefault(); setPage( 1 ); fetchItems(); } } className="conf-manager-search">
				<SelectControl
					value={ eventFilter }
					onChange={ ( val ) => { setEventFilter( val ); setPage( 1 ); } }
					options={ [
						{ label: __( 'All Events', 'conferencemanager' ), value: '' },
						...events.map( ( ev ) => ( {
							label: `${ ev.title }（${ ev.date_start?.substring( 0, 10 ) }）`,
							value: String( ev.id ),
						} ) ),
					] }
				/>
				<SelectControl
					value={ statusFilter }
					onChange={ setStatusFilter }
					options={ [
						{ label: __( 'All Statuses', 'conferencemanager' ), value: '' },
						...Object.entries( STATUS_LABELS ).map( ( [ v, l ] ) => ( { label: l, value: v } ) ),
					] }
				/>
				<SelectControl
					value={ methodFilter }
					onChange={ setMethodFilter }
					options={ [
						{ label: __( 'All Methods', 'conferencemanager' ), value: '' },
						...Object.entries( METHOD_LABELS ).map( ( [ v, l ] ) => ( { label: l, value: v } ) ),
					] }
				/>
				<Button type="submit" className="conf-manager-btn--primary">
					{ __( 'Search', 'conferencemanager' ) }
				</Button>
			</form>

			{ /* 売上集計カード */ }
			{ summary && (
				<div className="conf-manager-payment-summary">
					<div className="conf-manager-payment-summary__card is-completed">
						<div className="conf-manager-payment-summary__label">{ __( 'Paid', 'conferencemanager' ) }</div>
						<div className="conf-manager-payment-summary__value">&yen;{ ( summary.total.completed_amount + summary.total.completed_tax ).toLocaleString() }</div>
						<div className="conf-manager-payment-summary__count">{ summary.total.completed_count }{ __( 'items', 'conferencemanager' ) }</div>
					</div>
					<div className="conf-manager-payment-summary__card is-pending">
						<div className="conf-manager-payment-summary__label">{ __( 'Unpaid', 'conferencemanager' ) }</div>
						<div className="conf-manager-payment-summary__value">&yen;{ ( summary.total.pending_amount + summary.total.pending_tax ).toLocaleString() }</div>
						<div className="conf-manager-payment-summary__count">{ summary.total.pending_count }{ __( 'items', 'conferencemanager' ) }</div>
					</div>
					<div className="conf-manager-payment-summary__card">
						<div className="conf-manager-payment-summary__label">{ __( 'Stripe Fee', 'conferencemanager' ) }</div>
						<div className="conf-manager-payment-summary__value">&yen;{ ( summary.total.completed_fee || 0 ).toLocaleString() }</div>
					</div>
					{ summary.by_method && Object.keys( summary.by_method ).length > 1 && (
						<div className="conf-manager-payment-summary__card">
							<div className="conf-manager-payment-summary__label">{ __( 'Breakdown by Method', 'conferencemanager' ) }</div>
							{ Object.entries( summary.by_method ).map( ( [ method, data ] ) => (
								<div key={ method } style={ { fontSize: '13px', marginTop: '4px' } }>
									{ METHOD_LABELS[ method ] || method }: &yen;{ ( data.amount + data.tax ).toLocaleString() } ({ data.count }{ __( 'items', 'conferencemanager' ) })
								</div>
							) ) }
						</div>
					) }
				</div>
			) }

			<DataTable
				columns={ COLUMNS }
				rows={ items }
				total={ total }
				page={ page }
				perPage={ 20 }
				onPageChange={ setPage }
				loading={ loading }
			/>

			{ /* 入金確認モーダル */ }
			{ confirmModal && (
				<Modal
					title={ __( 'Confirm Payment', 'conferencemanager' ) }
					onRequestClose={ () => setConfirmModal( null ) }
				>
					<p>
						{ __( 'Payment ID:', 'conferencemanager' ) } { confirmModal.id } /
						{ ' ' }{ __( 'Name:', 'conferencemanager' ) } { confirmModal.member_name } /
						{ ' ' }{ __( 'Amount:', 'conferencemanager' ) } &yen;{ ( Number( confirmModal.amount ) + Number( confirmModal.tax || 0 ) ).toLocaleString() }
					</p>
					{ confirmModal.transfer_note && (
						<p style={ { padding: '8px 12px', marginBottom: '12px', background: '#fcf9e8', borderLeft: '4px solid #dba617' } }>
							<strong>{ __( 'Transfer Account Name Note', 'conferencemanager' ) }</strong>
							<br />{ confirmModal.transfer_note }
						</p>
					) }
					<TextControl
						label={ __( 'Transfer Name', 'conferencemanager' ) }
						value={ confirmName }
						onChange={ setConfirmName }
					/>
					<TextControl
						label={ __( 'Transfer Date', 'conferencemanager' ) }
						type="date"
						value={ confirmDate }
						onChange={ setConfirmDate }
					/>
					<div style={ { marginTop: '16px', display: 'flex', gap: '8px' } }>
						<Button variant="primary" onClick={ handleConfirm }>
							{ __( 'Confirm Payment', 'conferencemanager' ) }
						</Button>
						<Button variant="tertiary" onClick={ () => setConfirmModal( null ) }>
							{ __( 'Cancel', 'conferencemanager' ) }
						</Button>
					</div>
				</Modal>
			) }

			{ /* 返金モーダル */ }
			{ refundModal && (
				<Modal
					title={ __( 'Refund Processing', 'conferencemanager' ) }
					onRequestClose={ () => setRefundModal( null ) }
				>
					<p>
						{ __( 'Payment ID:', 'conferencemanager' ) } { refundModal.id } /
						{ ' ' }{ __( 'Name:', 'conferencemanager' ) } { refundModal.member_name } /
						{ ' ' }{ __( 'Payment method:', 'conferencemanager' ) } { METHOD_LABELS[ refundModal.method ] || refundModal.method }
					</p>
					<p>
						{ __( 'Amount:', 'conferencemanager' ) } &yen;{ ( Number( refundModal.amount ) + Number( refundModal.tax || 0 ) ).toLocaleString() }
					</p>
					<SelectControl
						label={ __( 'Refund Type', 'conferencemanager' ) }
						value={ refundType }
						onChange={ setRefundType }
						options={ [
							{ label: __( 'Full Refund', 'conferencemanager' ), value: 'full' },
							{ label: __( 'Partial Refund', 'conferencemanager' ), value: 'partial' },
						] }
					/>
					{ refundType === 'partial' && (
						<TextControl
							label={ __( 'Refund Amount (JPY)', 'conferencemanager' ) }
							type="number"
							value={ refundAmount }
							onChange={ setRefundAmount }
						/>
					) }
					<TextControl
						label={ __( 'Refund Reason', 'conferencemanager' ) }
						value={ refundReason }
						onChange={ setRefundReason }
					/>
					<p style={ { color: '#d63638', fontSize: '13px', marginTop: '8px' } }>
						{ refundModal.method === 'stripe'
							? __( 'Refund will be processed via Stripe. This action cannot be undone.', 'conferencemanager' )
							: __( 'Only a refund record will be saved. Actual refund requires a separate process.', 'conferencemanager' )
						}
					</p>
					<div style={ { marginTop: '16px', display: 'flex', gap: '8px' } }>
						<Button variant="primary" isDestructive isBusy={ refunding } disabled={ refunding } onClick={ handleRefund }>
							{ refunding ? __( 'Processing...', 'conferencemanager' ) : __( 'Process Refund', 'conferencemanager' ) }
						</Button>
						<Button variant="tertiary" onClick={ () => setRefundModal( null ) }>
							{ __( 'Cancel', 'conferencemanager' ) }
						</Button>
					</div>
				</Modal>
			) }

			{ /* 詳細モーダル */ }
			{ detailModal && (
				<Modal
					title={ __( 'Payment Details', 'conferencemanager' ) }
					onRequestClose={ () => setDetailModal( null ) }
				>
					<dl style={ { display: 'grid', gridTemplateColumns: '140px 1fr', gap: '8px 12px', margin: 0 } }>
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Payment ID', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0 } }>{ detailModal.id }</dd>
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Registration ID', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0 } }>{ detailModal.registration_id }</dd>
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Name', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0 } }>{ detailModal.member_name }</dd>
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Payment Method', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0 } }>{ METHOD_LABELS[ detailModal.method ] || detailModal.method }</dd>
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Amount (excl. tax)', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0 } }>&yen;{ Number( detailModal.amount ).toLocaleString() }</dd>
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Tax', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0 } }>&yen;{ Number( detailModal.tax || 0 ).toLocaleString() }</dd>
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Total', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0, fontWeight: 'bold' } }>&yen;{ ( Number( detailModal.amount ) + Number( detailModal.tax || 0 ) ).toLocaleString() }</dd>
						{ detailModal.fee > 0 && (
							<>
								<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Fees', 'conferencemanager' ) }</dt>
								<dd style={ { margin: 0 } }>&yen;{ Number( detailModal.fee ).toLocaleString() }</dd>
							</>
						) }
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Status', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0 } }>
							<span style={ { color: STATUS_COLORS[ detailModal.status ] || 'inherit', fontWeight: 'bold' } }>
								{ STATUS_LABELS[ detailModal.status ] || detailModal.status }
							</span>
						</dd>
						{ detailModal.gateway_txn_id && (
							<>
								<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Transaction ID', 'conferencemanager' ) }</dt>
								<dd style={ { margin: 0, fontSize: '12px', wordBreak: 'break-all' } }>{ detailModal.gateway_txn_id }</dd>
							</>
						) }
						{ detailModal.bank_transfer_name && (
							<>
								<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Transfer Name', 'conferencemanager' ) }</dt>
								<dd style={ { margin: 0 } }>{ detailModal.bank_transfer_name }</dd>
							</>
						) }
						{ detailModal.refund_amount > 0 && (
							<>
								<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Refund Amount', 'conferencemanager' ) }</dt>
								<dd style={ { margin: 0, color: '#d63638' } }>&yen;{ Number( detailModal.refund_amount ).toLocaleString() }</dd>
								<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Refund Reason', 'conferencemanager' ) }</dt>
								<dd style={ { margin: 0 } }>{ detailModal.refund_reason || '-' }</dd>
							</>
						) }
						<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Created', 'conferencemanager' ) }</dt>
						<dd style={ { margin: 0 } }>{ detailModal.created_at }</dd>
						{ detailModal.paid_at && (
							<>
								<dt style={ { fontWeight: 600, color: '#50575e' } }>{ __( 'Payment Date', 'conferencemanager' ) }</dt>
								<dd style={ { margin: 0 } }>{ detailModal.paid_at }</dd>
							</>
						) }
					</dl>
					<div style={ { marginTop: '16px' } }>
						<Button variant="tertiary" onClick={ () => setDetailModal( null ) }>
							{ __( 'Close', 'conferencemanager' ) }
						</Button>
					</div>
				</Modal>
			) }
		</div>
	);
}
