/**
 * External Dependencies
 */
import { __ } from '@wordpress/i18n';
import { TriangleAlert } from 'lucide-react';

/**
 * Internal Dependencies
 */
import { TextInput } from '@admin/components/TextInput';
import { Textarea } from '@admin/components/Textarea';
import { Select } from '@admin/components/Select';
import { Field } from './Field';

const AD_FORMAT_OPTIONS = [
	{ value: 'responsive', label: __( 'Responsive', 'advanced-ads' ) },
	{ value: 'fixed', label: __( 'Fixed size', 'advanced-ads' ) },
	{ value: 'auto', label: __( 'Auto format', 'advanced-ads' ) },
];

const AD_TYPE_OPTIONS = [
	{ value: 'display', label: __( 'Display', 'advanced-ads' ) },
	{ value: 'in-feed', label: __( 'In-feed', 'advanced-ads' ) },
	{ value: 'in-article', label: __( 'In-article', 'advanced-ads' ) },
];

const GAM_SIZE_OPTIONS = [
	{ value: 'responsive', label: __( 'Responsive', 'advanced-ads' ) },
	{ value: 'fixed', label: __( 'Fixed size', 'advanced-ads' ) },
];

function SizeInputs( { state, set } ) {
	return (
		<div className="flex flex-wrap items-end gap-3">
			<Field label={ __( 'Width', 'advanced-ads' ) }>
				<TextInput
					type="number"
					value={ state.adW }
					onChange={ ( v ) => set( 'adW', v ) }
					style={ { width: 110 } }
				/>
			</Field>
			<Field label={ __( 'Height', 'advanced-ads' ) }>
				<TextInput
					type="number"
					value={ state.adH }
					onChange={ ( v ) => set( 'adH', v ) }
					style={ { width: 110 } }
				/>
			</Field>
		</div>
	);
}

function AdSenseFields( { state, set, errors } ) {
	return (
		<section className="flex flex-col gap-4.5 border-t border-gray-200 pt-4.5">
			<h2 className="m-0 text-[15px] font-semibold">
				{ __( 'Connect Google AdSense', 'advanced-ads' ) }
			</h2>
			<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
				<Field
					label={ __( 'Publisher ID', 'advanced-ads' ) }
					error={ errors.pub }
					hint={ __(
						'Your Google AdSense publisher ID. It looks like pub- followed by 16 digits.',
						'advanced-ads'
					) }
				>
					<TextInput
						value={ state.pub }
						onChange={ ( v ) => set( 'pub', v ) }
						placeholder="pub-xxxxxxxxxxxxxxxx"
					/>
				</Field>
				<Field label={ __( 'Ad format', 'advanced-ads' ) }>
					<Select
						value={ state.adFormat }
						onChange={ ( v ) => set( 'adFormat', v ) }
						options={ AD_FORMAT_OPTIONS }
					/>
				</Field>
				<Field label={ __( 'Ad type', 'advanced-ads' ) }>
					<Select
						value={ state.adType }
						onChange={ ( v ) => set( 'adType', v ) }
						options={ AD_TYPE_OPTIONS }
					/>
				</Field>
			</div>
			{ state.adFormat === 'fixed' && (
				<SizeInputs state={ state } set={ set } />
			) }
			{ state.adFormat === 'responsive' && (
				<p className="m-0 rounded border border-gray-200 bg-gray-50 px-3 py-2.5 text-[12.5px] text-gray-600">
					{ __(
						'The ad will automatically adapt to the available space.',
						'advanced-ads'
					) }
				</p>
			) }
			<Field
				label={ __( 'Ad slot ID', 'advanced-ads' ) }
				optional
				hint={ __(
					'Optional. Use this when you want to display a specific AdSense ad unit.',
					'advanced-ads'
				) }
			>
				<TextInput
					value={ state.slot }
					onChange={ ( v ) => set( 'slot', v ) }
					placeholder="1234567890"
					style={ { maxWidth: 320 } }
				/>
			</Field>
		</section>
	);
}

function GamFields( { state, set, errors } ) {
	return (
		<section className="flex flex-col gap-4.5 border-t border-gray-200 pt-4.5">
			<h2 className="m-0 text-[15px] font-semibold">
				{ __( 'Configure your Ad Manager ad', 'advanced-ads' ) }
			</h2>
			<Field
				label={ __( 'Ad unit path', 'advanced-ads' ) }
				error={ errors.netName }
			>
				<TextInput
					value={ state.netName }
					onChange={ ( v ) => set( 'netName', v ) }
					placeholder="/1234567/homepage-top"
					style={ { maxWidth: 360 } }
				/>
			</Field>
			<Field
				label={ __( 'Ad code', 'advanced-ads' ) }
				error={ errors.code }
				hint={ __(
					'Paste the tag Google Ad Manager generated for this ad unit.',
					'advanced-ads'
				) }
			>
				<Textarea
					value={ state.netCode }
					onChange={ ( v ) => set( 'netCode', v ) }
					rows={ 7 }
					placeholder={ __(
						'<!-- Paste your ad code here -->',
						'advanced-ads'
					) }
				/>
			</Field>
			<div className="flex flex-wrap items-end gap-3">
				<Field label={ __( 'Ad size', 'advanced-ads' ) }>
					<Select
						value={ state.adFormat }
						onChange={ ( v ) => set( 'adFormat', v ) }
						options={ GAM_SIZE_OPTIONS }
					/>
				</Field>
				{ state.adFormat === 'fixed' && (
					<SizeInputs state={ state } set={ set } />
				) }
			</div>
		</section>
	);
}

function ImageFields( { state, set, errors } ) {
	const openLibrary = () => {
		if ( ! window.wp?.media ) {
			return;
		}

		const frame = window.wp.media( {
			title: __( 'Select image', 'advanced-ads' ),
			button: {
				text: __( 'Use this image', 'advanced-ads' ),
			},
			library: { type: 'image' },
			multiple: false,
		} );

		frame.on( 'select', () => {
			const attachment = frame
				.state()
				.get( 'selection' )
				.first()
				.toJSON();
			set( 'imageId', attachment.id );
			set( 'imageUrl', attachment.url || '' );
			if ( attachment.width ) {
				set( 'adW', String( attachment.width ) );
			}
			if ( attachment.height ) {
				set( 'adH', String( attachment.height ) );
			}
		} );

		frame.open();
	};

	return (
		<section className="flex flex-col gap-4.5 border-t border-gray-200 pt-4.5">
			<h2 className="m-0 text-[15px] font-semibold">
				{ __( 'Configure your image ad', 'advanced-ads' ) }
			</h2>
			<Field
				label={ __( 'Image', 'advanced-ads' ) }
				error={ errors.image }
			>
				<div className="flex flex-col gap-3">
					{ state.imageUrl ? (
						<img
							src={ state.imageUrl }
							alt=""
							className="max-h-40 max-w-xs rounded-sm border border-gray-200 object-contain"
						/>
					) : null }
					<div className="flex flex-wrap gap-2">
						<button
							type="button"
							onClick={ openLibrary }
							className="cursor-pointer rounded-md border border-border bg-white px-4 py-2 text-[13.5px] text-gray-700"
						>
							{ state.imageId
								? __( 'Change image', 'advanced-ads' )
								: __( 'Select image', 'advanced-ads' ) }
						</button>
						{ state.imageId ? (
							<button
								type="button"
								onClick={ () => {
									set( 'imageId', 0 );
									set( 'imageUrl', '' );
								} }
								className="cursor-pointer border-0 bg-transparent px-2 py-2 text-[13px] text-gray-500"
							>
								{ __( 'Remove', 'advanced-ads' ) }
							</button>
						) : null }
					</div>
				</div>
			</Field>
			<Field
				className="max-w-[360px]"
				label={ __( 'Destination URL', 'advanced-ads' ) }
				error={ errors.url }
			>
				<TextInput
					value={ state.affUrl }
					onChange={ ( v ) => set( 'affUrl', v ) }
					placeholder="https://example.com/..."
				/>
			</Field>
		</section>
	);
}

function ContentFields( { state, set, errors } ) {
	return (
		<section className="flex flex-col gap-4.5 border-t border-gray-200 pt-4.5">
			<h2 className="m-0 text-[15px] font-semibold">
				{ __( 'Write your rich content ad', 'advanced-ads' ) }
			</h2>
			<Field
				label={ __( 'Content', 'advanced-ads' ) }
				error={ errors.code }
				hint={ __(
					'In Advanced Ads this opens the WordPress editor, so you can format text and insert media.',
					'advanced-ads'
				) }
			>
				<Textarea
					value={ state.customCode }
					onChange={ ( v ) => set( 'customCode', v ) }
					rows={ 6 }
					placeholder={ __(
						'Write the text, links and images for this ad…',
						'advanced-ads'
					) }
				/>
			</Field>
		</section>
	);
}

function DummyFields() {
	return (
		<section className="flex flex-col gap-3 border-t border-gray-200 pt-4.5">
			<h2 className="m-0 text-[15px] font-semibold">
				{ __( 'Dummy ad', 'advanced-ads' ) }
			</h2>
			<p className="m-0 max-w-[560px] text-[13px] leading-relaxed text-gray-500">
				{ __(
					'A dummy ad renders a grey placeholder box instead of real advertising. Use it to check that your placements sit where you expect before you paste real ad code.',
					'advanced-ads'
				) }
			</p>
		</section>
	);
}

function PlainFields( { state, set, errors } ) {
	return (
		<section className="flex flex-col gap-4.5 border-t border-gray-200 pt-4.5">
			<h2 className="m-0 text-[15px] font-semibold">
				{ __( 'Add your ad code', 'advanced-ads' ) }
			</h2>
			<Field
				label={ __( 'HTML / JavaScript', 'advanced-ads' ) }
				error={ errors.code }
			>
				<Textarea
					value={ state.customCode }
					onChange={ ( v ) => set( 'customCode', v ) }
					rows={ 8 }
					placeholder={ __(
						'<!-- Paste your ad code here -->',
						'advanced-ads'
					) }
				/>
			</Field>
			<div className="flex items-start gap-2.5 rounded border border-orange-200 bg-orange-50 px-3.5 py-3">
				<TriangleAlert className="mt-0.5 size-4 shrink-0 text-orange-700" />
				<span className="text-[12.5px] leading-relaxed text-orange-900">
					{ __(
						'Only add code from a source you trust. Custom code runs on every page where this ad is shown.',
						'advanced-ads'
					) }
				</span>
			</div>
		</section>
	);
}

const FIELDS_BY_SOURCE = {
	adsense: AdSenseFields,
	gam: GamFields,
	image: ImageFields,
	content: ContentFields,
	dummy: DummyFields,
	plain: PlainFields,
};

export function AdConfigFields( { state, set, errors } ) {
	const Fields = FIELDS_BY_SOURCE[ state.source ];
	if ( ! Fields ) {
		return null;
	}
	return <Fields state={ state } set={ set } errors={ errors } />;
}
