import { useState, useEffect, useRef } from '@wordpress/element';
import { Button, Card, CardBody, CardHeader, Spinner } from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';

function downloadJson( data, filename ) {
	const blob = new Blob( [ JSON.stringify( data, null, 2 ) ], { type: 'application/json' } );
	const url = URL.createObjectURL( blob );
	const a = document.createElement( 'a' );
	a.href = url;
	a.download = filename;
	document.body.appendChild( a );
	a.click();
	document.body.removeChild( a );
	URL.revokeObjectURL( url );
}

export default function ToolList( { navigate } ) {
	const [ tools, setTools ] = useState( [] );
	const [ loading, setLoading ] = useState( true );
	const [ deleting, setDeleting ] = useState( null );
	const [ importing, setImporting ] = useState( false );
	const [ notice, setNotice ] = useState( null );
	const fileInputRef = useRef();

	useEffect( () => {
		apiFetch( { path: 'wlconduit/v1/tools' } )
			.then( ( data ) => setTools( data || [] ) )
			.catch( () => setTools( window.wlconduitData?.tools || [] ) )
			.finally( () => setLoading( false ) );
	}, [] );

	useEffect( () => {
		if ( ! notice ) {
			return;
		}
		const timer = setTimeout( () => setNotice( null ), 5000 );
		return () => clearTimeout( timer );
	}, [ notice ] );

	async function handleDelete( id ) {
		if ( ! window.confirm( 'Are you sure you want to delete this tool?' ) ) {
			return;
		}

		setDeleting( id );
		try {
			await apiFetch( {
				path: `wlconduit/v1/tools/${ id }`,
				method: 'DELETE',
			} );
			setTools( tools.filter( ( t ) => t.id !== id ) );
		} catch ( err ) {
			window.alert( 'Failed to delete tool.' );
		}
		setDeleting( null );
	}

	async function handleExport( ids ) {
		try {
			const path = ids
				? `wlconduit/v1/tools/export?ids=${ ids }`
				: 'wlconduit/v1/tools/export';
			const data = await apiFetch( { path } );
			const filename = ids && ! ids.includes( ',' )
				? `ai-conduit-${ ( data.tools[ 0 ]?.tool_name || 'tool' ) }.json`
				: 'ai-conduit-tools-export.json';
			downloadJson( data, filename );
		} catch ( err ) {
			setNotice( { type: 'error', message: 'Failed to export tools.' } );
		}
	}

	function handleImportClick() {
		fileInputRef.current.value = '';
		fileInputRef.current.click();
	}

	function handleFileSelect( event ) {
		const file = event.target.files[ 0 ];
		if ( ! file ) {
			return;
		}

		const reader = new FileReader();
		reader.onload = async ( e ) => {
			let parsed;
			try {
				parsed = JSON.parse( e.target.result );
			} catch ( err ) {
				setNotice( { type: 'error', message: 'Invalid JSON file.' } );
				return;
			}

			if ( parsed.format !== 'ai-conduit-tools' ) {
				setNotice( { type: 'error', message: 'Not a valid AI Conduit export file.' } );
				return;
			}

			setImporting( true );
			try {
				const response = await apiFetch( {
					path: 'wlconduit/v1/tools/import',
					method: 'POST',
					data: parsed,
				} );

				const created = ( response.results || [] ).filter( ( r ) => r.status === 'created' );
				const errors = ( response.results || [] ).filter( ( r ) => r.status === 'error' );

				let message = '';
				if ( created.length > 0 ) {
					const names = created.map( ( r ) => r.tool_name ).join( ', ' );
					message += `Imported ${ created.length } tool(s): ${ names }.`;
				}
				if ( errors.length > 0 ) {
					const msgs = errors.map( ( r ) => r.message ).join( '; ' );
					message += ( message ? ' ' : '' ) + `${ errors.length } failed: ${ msgs }`;
				}

				setNotice( {
					type: errors.length > 0 && created.length === 0 ? 'error' : 'success',
					message: message || 'Import completed.',
				} );

				// Refresh the tools list.
				const refreshed = await apiFetch( { path: 'wlconduit/v1/tools' } );
				setTools( refreshed || [] );
			} catch ( err ) {
				setNotice( { type: 'error', message: err.message || 'Import failed.' } );
			}
			setImporting( false );
		};
		reader.readAsText( file );
	}

	return (
		<div className="aic-tool-list">
			<div className="aic-header">
				<h1>AI Conduit - Tools</h1>
				<div className="aic-header-actions">
					<Button variant="primary" onClick={ () => navigate( '/tools/new' ) }>
						Create New Tool
					</Button>
					<Button
						variant="secondary"
						onClick={ handleImportClick }
						isBusy={ importing }
						disabled={ importing }
					>
						Import
					</Button>
					{ tools.length > 0 && (
						<Button variant="secondary" onClick={ () => handleExport() }>
							Export All
						</Button>
					) }
					{ window.wlconduitData?.isAdmin && (
						<Button variant="secondary" onClick={ () => navigate( '/settings' ) }>
							Settings
						</Button>
					) }
					<Button variant="tertiary" onClick={ () => navigate( '/instructions' ) }>
						Instructions
					</Button>
				</div>
			</div>

			<input
				type="file"
				accept=".json"
				ref={ fileInputRef }
				onChange={ handleFileSelect }
				style={ { display: 'none' } }
			/>

			{ notice && (
				<div className={ `aic-notice aic-notice--${ notice.type }` }>
					<p>{ notice.message }</p>
					<Button
						isSmall
						variant="tertiary"
						onClick={ () => setNotice( null ) }
					>
						Dismiss
					</Button>
				</div>
			) }

			{ loading ? (
				<Spinner />
			) : tools.length === 0 ? (
				<Card>
					<CardBody>
						<p className="aic-empty-state">
							No tools created yet. Click "Create New Tool" to get started.
						</p>
					</CardBody>
				</Card>
			) : (
				<div className="aic-tools-grid">
					{ tools.map( ( tool ) => (
						<Card key={ tool.id } className="aic-tool-card">
							<CardHeader>
								<h3>{ tool.tool_name }</h3>
							</CardHeader>
							<CardBody>
								<p className="aic-tool-description">
									{ tool.description || 'No description' }
								</p>
								<div className="aic-tool-meta">
									<span>{ tool.block_count } block(s)</span>
									<span>Modified: { new Date( tool.modified ).toLocaleDateString() }</span>
								</div>
								<div className="aic-tool-actions">
									<Button
										variant="secondary"
										onClick={ () => navigate( `/tools/${ tool.id }` ) }
									>
										Edit
									</Button>
									<Button
										variant="secondary"
										onClick={ () => handleExport( String( tool.id ) ) }
									>
										Export
									</Button>
									<Button
										variant="tertiary"
										isDestructive
										isBusy={ deleting === tool.id }
										onClick={ () => handleDelete( tool.id ) }
									>
										Delete
									</Button>
								</div>
							</CardBody>
						</Card>
					) ) }
				</div>
			) }
		</div>
	);
}
