import React from 'react';
import { __ } from '@wordpress/i18n';
import {
	Button,
	TextControl,
	SelectControl,
	ToggleControl,
	PanelRow,
} from '@wordpress/components';
import { plus, arrowUp, arrowDown, trash } from '@wordpress/icons';

const FIELD_TYPES = [
	{ label: __('Text', 'bookify'), value: 'text' },
	{ label: __('Textarea', 'bookify'), value: 'textarea' },
	{ label: __('Number', 'bookify'), value: 'number' },
	{ label: __('Email', 'bookify'), value: 'email' },
	{ label: __('Select (Dropdown)', 'bookify'), value: 'select' },
];

const slugify = (value) => {
	return String(value || '')
		.toLowerCase()
		.trim()
		.replace(/[^a-z0-9]+/g, '_')
		.replace(/^_+|_+$/g, '')
		.replace(/_+/g, '_');
};

const createUniqueId = (label, existingIds) => {
	const base = slugify(label) || `field_${Date.now()}`;
	let id = base;
	let counter = 1;

	while (existingIds.includes(id)) {
		id = `${base}_${counter}`;
		counter += 1;
	}

	return id;
};

const createEmptyField = (existingFields = []) => {
	const existingIds = existingFields.map((field) => field.id);
	const index = existingFields.length + 1;

	return {
		clientId: `field_${Date.now()}_${index}`,
		id: createUniqueId(`custom_field_${index}`, existingIds),
		type: 'text',
		label: '',
		required: false,
		placeholder: '',
		options: [],
	};
};

const ensureClientIds = (fields = []) => {
	return fields.map((field, index) => ({
		...field,
		clientId: field.clientId || `legacy_${field.id || index}`,
	}));
};

const updateFieldAtIndex = (fields, index, updates) => {
	return fields.map((field, fieldIndex) => {
		if (fieldIndex !== index) {
			return field;
		}

		const nextField = { ...field, ...updates };

		if (updates.type === 'select' && !Array.isArray(nextField.options)) {
			nextField.options = [];
		}

		if (updates.type && updates.type !== 'select') {
			nextField.options = [];
		}

		return nextField;
	});
};

const moveField = (fields, fromIndex, toIndex) => {
	if (toIndex < 0 || toIndex >= fields.length || fromIndex === toIndex) {
		return fields;
	}

	const nextFields = [...fields];
	const [movedField] = nextFields.splice(fromIndex, 1);
	nextFields.splice(toIndex, 0, movedField);
	return nextFields;
};

const CustomFieldsInspector = ({ fields = [], onChange }) => {
	const safeFields = ensureClientIds(Array.isArray(fields) ? fields : []);

	const updateFields = (nextFields) => {
		onChange(ensureClientIds(nextFields));
	};

	const addField = () => {
		updateFields([...safeFields, createEmptyField(safeFields)]);
	};

	const removeField = (index) => {
		updateFields(safeFields.filter((_, fieldIndex) => fieldIndex !== index));
	};

	const updateField = (index, updates) => {
		updateFields(updateFieldAtIndex(safeFields, index, updates));
	};

	const syncFieldIdFromLabel = (index) => {
		const field = safeFields[index];
		if (!field?.label?.trim()) {
			return;
		}

		const existingIds = safeFields
			.filter((_, fieldIndex) => fieldIndex !== index)
			.map((item) => item.id);
		const nextId = createUniqueId(field.label, existingIds);

		if (nextId !== field.id) {
			updateField(index, { id: nextId });
		}
	};

	const moveFieldUp = (index) => {
		updateFields(moveField(safeFields, index, index - 1));
	};

	const moveFieldDown = (index) => {
		updateFields(moveField(safeFields, index, index + 1));
	};

	const addSelectOption = (fieldIndex) => {
		const field = safeFields[fieldIndex];
		const options = Array.isArray(field.options) ? [...field.options] : [];
		const optionNumber = options.length + 1;

		options.push({
			label: `${__('Option', 'bookify')} ${optionNumber}`,
			value: `option_${optionNumber}`,
		});

		updateField(fieldIndex, { options });
	};

	const updateSelectOption = (fieldIndex, optionIndex, key, value) => {
		const field = safeFields[fieldIndex];
		const options = (field.options || []).map((option, index) => {
			if (index !== optionIndex) {
				return option;
			}

			const nextOption = { ...option, [key]: value };

			if (key === 'label') {
				nextOption.value = slugify(value) || option.value;
			}

			return nextOption;
		});

		updateField(fieldIndex, { options });
	};

	const removeSelectOption = (fieldIndex, optionIndex) => {
		const field = safeFields[fieldIndex];
		const options = (field.options || []).filter((_, index) => index !== optionIndex);
		updateField(fieldIndex, { options });
	};

	return (
		<div style={{ marginTop: '8px' }}>
			<p style={{ margin: '0 0 12px', color: '#646970', fontSize: '12px', lineHeight: 1.5 }}>
				{__('Add extra fields that appear in the Information step after the phone field.', 'bookify')}
			</p>

			{safeFields.length === 0 && (
				<p style={{ margin: '0 0 12px', color: '#8c8f94', fontSize: '12px', fontStyle: 'italic' }}>
					{__('No custom fields yet. Click "Add Field" to create one.', 'bookify')}
				</p>
			)}

			{safeFields.map((field, index) => (
				<div
					key={field.clientId}
					style={{
						border: '1px solid #dcdcde',
						borderRadius: '4px',
						padding: '12px',
						marginBottom: '12px',
						background: '#fff',
					}}
				>
					<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
						<strong style={{ fontSize: '12px' }}>
							{field.label || __('New Field', 'bookify')}
						</strong>
						<div style={{ display: 'flex', gap: '4px' }}>
							<Button
								icon={arrowUp}
								label={__('Move up', 'bookify')}
								onClick={() => moveFieldUp(index)}
								disabled={index === 0}
								size="small"
							/>
							<Button
								icon={arrowDown}
								label={__('Move down', 'bookify')}
								onClick={() => moveFieldDown(index)}
								disabled={index === safeFields.length - 1}
								size="small"
							/>
							<Button
								icon={trash}
								label={__('Remove field', 'bookify')}
								onClick={() => removeField(index)}
								isDestructive
								size="small"
							/>
						</div>
					</div>

					<TextControl
						label={__('Field Label', 'bookify')}
						value={field.label || ''}
						onChange={(value) => updateField(index, { label: value })}
						onBlur={() => syncFieldIdFromLabel(index)}
						placeholder={__('e.g. Company Name', 'bookify')}
					/>

					<SelectControl
						label={__('Field Type', 'bookify')}
						value={field.type || 'text'}
						options={FIELD_TYPES}
						onChange={(value) => updateField(index, { type: value })}
					/>

					<TextControl
						label={__('Placeholder', 'bookify')}
						value={field.placeholder || ''}
						onChange={(value) => updateField(index, { placeholder: value })}
						placeholder={__('Optional placeholder text', 'bookify')}
					/>

					<ToggleControl
						label={__('Required field', 'bookify')}
						checked={Boolean(field.required)}
						onChange={(value) => updateField(index, { required: value })}
					/>

					{field.type === 'select' && (
						<div style={{ marginTop: '8px' }}>
							<p style={{ margin: '0 0 8px', fontWeight: 600, fontSize: '12px' }}>
								{__('Dropdown Options', 'bookify')}
							</p>

							{(field.options || []).map((option, optionIndex) => (
								<div key={`${field.clientId}-option-${optionIndex}`} style={{ display: 'flex', gap: '8px', marginBottom: '8px', alignItems: 'flex-end' }}>
									<div style={{ flex: 1 }}>
										<TextControl
											label={__('Option Label', 'bookify')}
											value={option.label || ''}
											onChange={(value) => updateSelectOption(index, optionIndex, 'label', value)}
										/>
									</div>
									<Button
										icon={trash}
										label={__('Remove option', 'bookify')}
										onClick={() => removeSelectOption(index, optionIndex)}
										isDestructive
										size="small"
									/>
								</div>
							))}

							<Button variant="secondary" onClick={() => addSelectOption(index)} size="small">
								{__('Add Option', 'bookify')}
							</Button>
						</div>
					)}
				</div>
			))}

			<PanelRow>
				<Button variant="primary" icon={plus} onClick={addField}>
					{__('Add Field', 'bookify')}
				</Button>
			</PanelRow>
		</div>
	);
};

export default CustomFieldsInspector;
