import { Button, Card, CardBody, CardHeader, TextControl } from '@wordpress/components';
import { useState } from '@wordpress/element';

export default function Instructions( { navigate } ) {
	const endpointUrl = window.wlconduitData?.mcpEndpoint || '';
	const profileUrl = window.wlconduitData?.profileUrl || '';
	const siteName = window.wlconduitData?.siteName || 'my-site';
	const currentUser = window.wlconduitData?.currentUser || 'your_username';
	const [ copied, setCopied ] = useState( false );
	const [ appPassword, setAppPassword ] = useState( '' );

	function copyEndpoint() {
		navigator.clipboard.writeText( endpointUrl );
		setCopied( true );
		setTimeout( () => setCopied( false ), 2000 );
	}

	const siteSlug = siteName.toLowerCase().replace( /[^a-z0-9]+/g, '-' );
	const base64Creds = appPassword
		? btoa( currentUser + ':' + appPassword )
		: 'YOUR_BASE64_CREDENTIALS';

	return (
		<div className="aic-instructions">
			<div className="aic-header">
				<Button variant="tertiary" onClick={ () => navigate( '/' ) }>
					&larr; Back to Tools
				</Button>
				<h1>AI Conduit - Instructions</h1>
			</div>

			<Card className="aic-card-highlight">
				<CardHeader><h3>Your MCP Endpoint</h3></CardHeader>
				<CardBody>
					<p>This is the URL your AI client needs to connect to your site:</p>
					<div className="aic-endpoint-box">
						<code>{ endpointUrl }</code>
						<Button variant="secondary" isSmall onClick={ copyEndpoint }>
							{ copied ? 'Copied!' : 'Copy' }
						</Button>
					</div>
				</CardBody>
			</Card>

			<Card>
				<CardHeader><h3>What is AI Conduit?</h3></CardHeader>
				<CardBody>
					<p>
						AI Conduit lets you create MCP (Model Context Protocol) tools that expose your
						WordPress content to AI assistants like Claude, Cursor, and other MCP-compatible clients.
					</p>
					<p>
						Think of it as building a bridge between your WordPress site and AI.
						You decide exactly what data the AI can access &mdash; which posts, which fields,
						which filters &mdash; using a simple drag-and-drop builder.
					</p>
				</CardBody>
			</Card>

			<Card>
				<CardHeader><h3>How to Create a Tool</h3></CardHeader>
				<CardBody>
					<ol className="aic-steps">
						<li>Go to <strong>AI Conduit &gt; Tools</strong> and click <strong>Create New Tool</strong>.</li>
						<li>Give your tool a name and description. The description helps the AI understand when to use this tool.</li>
						<li>Drag content blocks (like Posts) from the left panel onto the builder canvas.</li>
						<li>Configure each block &mdash; select which fields to include, which custom fields and taxonomies to expose, and which filters the AI can use.</li>
						<li>Preview the generated JSON schema to see exactly what the AI will see.</li>
						<li>Click <strong>Publish</strong>. Your tool is now live and available to connected AI clients.</li>
					</ol>
				</CardBody>
			</Card>

			<Card>
				<CardHeader><h3>Step 1: Create an Application Password</h3></CardHeader>
				<CardBody>
					<ol className="aic-steps">
						<li>
							Go to your{ ' ' }
							<a href={ profileUrl } target="_blank" rel="noopener noreferrer">
								profile page
							</a>{ ' ' }
							in WordPress.
						</li>
						<li>Scroll down to the &quot;Application Passwords&quot; section.</li>
						<li>Enter a name (e.g., &quot;AI Client&quot;) and click &quot;Add New Application Password&quot;.</li>
						<li>Copy the generated password and paste it below:</li>
					</ol>

					<TextControl
						label="Application Password"
						help={ `Username: ${ currentUser } (logged in)` }
						placeholder="Paste your application password here"
						value={ appPassword }
						onChange={ setAppPassword }
					/>

					{ appPassword && (
						<div className="aic-base64-output">
							<p><strong>Your Base64 credentials (auto-generated):</strong></p>
							<div className="aic-endpoint-box">
								<code>{ base64Creds }</code>
								<Button variant="secondary" isSmall onClick={ () => {
									navigator.clipboard.writeText( base64Creds );
								} }>
									Copy
								</Button>
							</div>
							<p className="aic-selector-hint">
								The configs below are pre-filled with your credentials. Just copy and paste.
							</p>
						</div>
					) }
				</CardBody>
			</Card>

			<Card>
				<CardHeader><h3>Step 2: Connect Your AI Client</h3></CardHeader>
				<CardBody>
					<h4>Claude Code (CLI)</h4>
					<p>Run this in your terminal:</p>
					<pre className="aic-code-block">{ `claude mcp add ${ siteSlug } --transport http ${ endpointUrl } --header "Authorization: Basic ${ base64Creds }"` }</pre>

					<h4>Claude Desktop</h4>
					<p>
						Requires{ ' ' }
						<a href="https://nodejs.org/" target="_blank" rel="noopener noreferrer">Node.js</a>{ ' ' }
						installed on your machine. Add this to your <code>claude_desktop_config.json</code>:
					</p>
					<p className="aic-selector-hint">
						<strong>Windows users:</strong> If <code>npx</code> fails with &quot;C:\Program is not recognized&quot;,
						replace <code>&quot;npx&quot;</code> with <code>&quot;C:\\PROGRA~1\\nodejs\\npx.cmd&quot;</code> (short path avoids spaces).
					</p>
					<pre className="aic-code-block">{ JSON.stringify( {
						mcpServers: {
							[ siteSlug ]: {
								command: 'npx',
								args: [
									'-y',
									'mcp-remote',
									endpointUrl,
									'--header',
									'Authorization: Basic ' + base64Creds,
								],
							},
						},
					}, null, 2 ) }</pre>
					<p className="aic-selector-hint">
						AI Conduit works with any AI client that supports the Model Context Protocol (MCP) over Streamable HTTP
						with Basic Auth. Use the MCP endpoint URL and credentials above to configure your preferred client.
					</p>
				</CardBody>
			</Card>

			<Card>
				<CardHeader><h3>Available Content Blocks</h3></CardHeader>
				<CardBody>
					<table className="widefat">
						<thead>
							<tr>
								<th>Block</th>
								<th>What it does</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td><strong>Posts</strong></td>
								<td>Fetch posts, pages, or any custom post type. Supports filtering by category, tag, author, date, custom fields, and custom taxonomies.</td>
							</tr>
							<tr>
								<td><strong>Users</strong></td>
								<td>Retrieve user information &mdash; names, roles, and registration details.</td>
							</tr>
							<tr>
								<td><strong>Site Info</strong></td>
								<td>Get site-level information like title, tagline, URL, language, and active theme.</td>
							</tr>
							<tr>
								<td><strong>Comments</strong></td>
								<td>Fetch comments on posts &mdash; content, author, date, and approval status.</td>
							</tr>
						</tbody>
					</table>
				</CardBody>
			</Card>

			<Card>
				<CardHeader><h3>Security</h3></CardHeader>
				<CardBody>
					<ul>
						<li>All MCP requests require authentication via Application Passwords.</li>
						<li>Tools are read-only &mdash; AI clients cannot create, modify, or delete any content on your site.</li>
						<li>Only the fields and filters you explicitly configure in the builder are exposed.</li>
						<li>All requests are logged for auditing (can be configured in Settings).</li>
						<li>Application Passwords require HTTPS in production environments.</li>
					</ul>
				</CardBody>
			</Card>
		</div>
	);
}
