import React, { useEffect, useState } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { api } from '../api';
import { Card, Button, Badge, Notice, PageState } from '../components/ui';
import Explain from '../components/Explain';

export default function Htaccess() {
	const [data, setData] = useState(null);
	const [block, setBlock] = useState('');
	const [problems, setProblems] = useState([]);
	const [busy, setBusy] = useState(false);
	const [saved, setSaved] = useState(false);
	const [error, setError] = useState(null);

	const load = () =>
		api
			.get('/htaccess')
			.then((d) => {
				setData(d);
				setBlock(d.ours || '');
			})
			.catch((e) => setError(e.message));

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

	if (!data) return <PageState error={error} />;

	if (!data.supported) {
		return (
			<Card title=".htaccess" subtitle={__('Not applicable on this server', 'ai-rank-suite')}>
				<Notice tone="info">{__('This site runs on', 'ai-rank-suite')} <code>{data.server || __('a server', 'ai-rank-suite')}</code>{__(', which does not read', 'ai-rank-suite')} <code>.htaccess</code> {__('at all. Nginx and Caddy need the equivalent rules in the server configuration, which only your host can change — editing a file here would do nothing and look like it worked.', 'ai-rank-suite')}
				</Notice>
			</Card>
		);
	}

	const check = async (value) => {
		setBlock(value);
		try {
			const r = await api.post('/htaccess/check', { block: value });
			setProblems(r.problems || []);
		} catch {
			// Checking is advisory; the save path validates again server-side.
		}
	};

	const save = async () => {
		setBusy(true);
		setError(null);
		try {
			const next = await api.put('/htaccess', { block });
			setData(next);
			setSaved(true);
			setProblems([]);
			setTimeout(() => setSaved(false), 2400);
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const restore = async (id) => {
		setBusy(true);
		setError(null);
		try {
			const next = await api.post('/htaccess/restore', { id });
			setData(next);
			setBlock(next.ours || '');
		} catch (e) {
			setError(e.message);
		} finally {
			setBusy(false);
		}
	};

	const addRecipe = (r) => check(`${block ? `${block}\n\n` : ''}${r.body}`);

	return (
		<div className="ars-page">
			<Card
				title=".htaccess"
				subtitle={__('Server rules — caching, compression, security headers and redirects', 'ai-rank-suite')}
				action={
					data.writable ? (
						<Badge tone="good">{__('Writable', 'ai-rank-suite')}</Badge>
					) : (
						<Badge tone="serious">{__('Read-only', 'ai-rank-suite')}</Badge>
					)
				}
			>
				<div className="grid gap-3">
					<Explain title={__('Read this before you edit', 'ai-rank-suite')} open={!block}>
						<p>
							{__('A stray character here does not produce a warning — it produces a 500 on every URL of the site, including wp-admin, which would leave you unable to use this plugin to undo it.', 'ai-rank-suite')}
						</p>
						<p>{__('So only', 'ai-rank-suite')} <em>{__('our', 'ai-rank-suite')}</em> {__('block is editable. WordPress’s own rewrite rules and anything your host put there are read-only and preserved byte for byte. Every save takes a backup first, the last ten are kept, and you can restore any of them from this screen — recovery never needs FTP.', 'ai-rank-suite')}
						</p>
					</Explain>

					{!data.writable && (
						<Notice tone="warning">
							<code>{data.path}</code> {__('is not writable, so nothing here can be saved. Either make it writable, or copy the block below and paste it into the file yourself.', 'ai-rank-suite')}
						</Notice>
					)}

					<div>
						<label className="block font-medium mb-1">{__('Your rules', 'ai-rank-suite')}</label>
						<textarea
							rows={14}
							className="ars-mono"
							style={{ fontSize: 12, lineHeight: 1.6, whiteSpace: 'pre', overflowWrap: 'normal', overflowX: 'auto' }}
							value={block}
							placeholder={__('# Add Apache directives here. The BEGIN/END markers are added for you.', 'ai-rank-suite')}
							onChange={(e) => check(e.target.value)}
						/>
						<p className="m-0 mt-1.5 text-[11.5px]" style={{ color: 'var(--ars-ink-3)' }}>
							{sprintf(__('%1$s · %2$s KB total on disk', 'ai-rank-suite'), data.path, (data.bytes / 1024).toFixed(1))}
						</p>
					</div>

					{problems.length > 0 && (
						<Notice tone="serious">
							<strong>{__('Not saveable yet:', 'ai-rank-suite')}</strong>
							<ul className="m-0 mt-1 pl-5">
								{problems.map((p, i) => (
									<li key={i}>{p}</li>
								))}
							</ul>
						</Notice>
					)}

					<div className="flex items-center gap-2 flex-wrap">
						<Button onClick={save} busy={busy} disabled={!data.writable || problems.length > 0}>{__('Save to .htaccess', 'ai-rank-suite')}</Button>
						<Button variant="ghost" onClick={load} disabled={busy}>{__('Discard changes', 'ai-rank-suite')}</Button>
						{saved && <Badge tone="good">✓ {__('Saved · backup taken', 'ai-rank-suite')}</Badge>}
					</div>
					{error && <Notice tone="serious">{error}</Notice>}
				</div>
			</Card>

			<Card title={__('Ready-made blocks', 'ai-rank-suite')} subtitle={__('So nobody has to write Apache from memory', 'ai-rank-suite')}>
				<div className="grid gap-2 sm:grid-cols-2">
					{(data.recipes || []).map((r) => (
						<button key={r.id} type="button" onClick={() => addRecipe(r)} className="ars-pick">
							<span className="ars-pick-title">
								{r.label}
								<span style={{ marginLeft: 'auto', color: 'var(--ars-brand)', fontSize: 12 }}>+ {__('Add', 'ai-rank-suite')}</span>
							</span>
							<span className="ars-pick-note">{r.desc}</span>
						</button>
					))}
				</div>
			</Card>

			<Card
				title={__('Backups', 'ai-rank-suite')}
				subtitle={
					data.backups.length > 0
						? __('The last ten states of the whole file, newest first', 'ai-rank-suite')
						: __('A backup is taken automatically before every save', 'ai-rank-suite')
				}
			>
				{data.backups.length === 0 ? (
					<p className="m-0 text-[12.5px]" style={{ color: 'var(--ars-ink-3)' }}>{__('Nothing saved yet, so there is nothing to roll back to.', 'ai-rank-suite')}</p>
				) : (
					<div className="ars-table-wrap"><table className="ars-table">
						<thead>
							<tr>
								<th>{__('Taken', 'ai-rank-suite')}</th>
								<th className="is-num is-narrow">{__('Size', 'ai-rank-suite')}</th>
								<th className="is-num is-mid" />
							</tr>
						</thead>
						<tbody>
							{data.backups.map((b) => (
								<tr key={b.id}>
									<td>{new Date(b.time * 1000).toLocaleString()}</td>
									<td className="is-num">{(b.bytes / 1024).toFixed(1)} KB</td>
									<td className="is-num">
										<Button variant="ghost" onClick={() => restore(b.id)} disabled={busy}>{__('Restore', 'ai-rank-suite')}</Button>
									</td>
								</tr>
							))}
						</tbody>
					</table></div>
				)}
			</Card>
		</div>
	);
}
