import { saveLayoutData } from '../services/LayoutService';
import ModalText from './modals/ModalText';

const LayoutEditor = () => {

	// Blocks
	const [blocks, setBlocks] = useState([]);// Current blocks on the grid
	const [blockContent, setBlockContent] = useState([]);// Content(Title) of current block
	const [editingBlock, setEditingBlock] = useState(null);// Currently edited block

	// Modals
	const [isModalOpen, setModalOpen] = useState(false);
	const [currentModalType, setCurrentModalType] = useState('');

	const handleBlockData = (block) => {
		
		setEditingBlock(block);// Set the block that is currently being edited
		setBlockContent(block.content);// Pre-populate with current block content
		setCurrentModalType(block.type);// Set the type based on the block type being edited
		
		openModal();
	};

	const saveBlockData = (data) => {
		
		setBlocks((prevBlocks) => 
			prevBlocks.map((block) => (block.i === data.i ? { ...block, ...data } : block))
		);
		
		closeModal();// Close the modal after saving
	};
	
	return (
	
		<div className="container-md">
			{isModalOpen && currentModalType === 'text' && (
				<ModalText
					isOpen={isModalOpen}
					onRequestClose={closeModal}
					blockData={editingBlock}
					onSave={saveBlockData}
				/>
			)}
		</div>
	);
}

//src/components/main/blocks/ModalText.js
import React, { useState, useEffect } from 'react';

const ModalText = ({ isOpen, onRequestClose, onSave, blockData }) => {
	
	const [text, setText] = useState('');
	const handleSubmit = async (e) => {
		
		e.preventDefault();
		const newBlock = {
			
			id: 'block-' + new Date().getTime(),// Unique ID
			content,
			type
		}
		
		try {
			await saveUserLayout(newBlock.id, newBlock);
			console.log('Modal - Text: Saved successfully.');
		}
		catch (error) {
			
			console.error('Modal - Text: Error saving:', error);
		}
	};
	
	return (
		
		<>
			<div className={`modal fade ${isOpen ? "show" : ""}`} style={{ display: isOpen ? "block" : "none" }} tabIndex="-1" role="dialog">
				<div className="modal-dialog" style={{ transform: 'translateY(50px)' }} role="document">
					<div className="modal-content">
						<div className="modal-header">
							<h5 className="modal-title">Text Block</h5>
							<button type="button" className="btn-close" onClick={onRequestClose} aria-label="Close"></button>
						</div>
						<div className="modal-body">
							<form onSubmit={handleSubmit}>
								<div className="mb-3">
									<label htmlFor="Text" className="form-label">Text:</label>
									<input
										type="text"
										id="textInput"
										className="form-control"
										value={text}// Bind the input value to state
										onChange={(e) => setText(e.target.value)}
										placeholder="Enter text"
										required
									/>
								</div>
								<button type="submit" className="btn btn-primary">Save</button>
								<button type="button" className="btn btn-secondary" onClick={onRequestClose}>Cancel</button>
							</form>
						</div>
					</div>
				</div>
			</div>
			{isOpen && <div className="modal-backdrop fade show"></div>}
		</>
	);
};

export default ModalText;


// src/services/UserService.js
import IndexedDB from '../utils/indexedDB';

/**
* Database
* Ensure the database is opened and the store is created
*/
const layoutDB = new IndexedDB('ReactCard', 1);
const openDatabase = async () => {
	
	try {
		await layoutDB.open();
	}
	catch (error) {
		
		console.error("Failed to open IndexedDB:", error);
		throw error;
	}
};

/**
* Fetch Data
* @param {string} userId - The unique ID of the user.
* @returns {object|null} - Returns the user's layout object or null if not found.
*/
export const fetchLayoutData = async (layoutId) => {
	
	await openDatabase();
	try {
		const storedLayoutData = await layoutDB.getData('LayoutData', layoutId);
		return storedLayoutData || null;// Returns user data or null
	}
	catch (error) {
		
		console.error("Error fetching user layout:", error);
		throw error;
	}
};

/**
* Save Data
* @param {string} userId - The unique ID of the user.
* @param {object} layout - The layout object to save.
*/
export const saveLayoutData = async (layoutId, layoutData) => {
	
	await openDatabase();
	try {
		await layoutDB.putData('UserData', { id: layoutId, ...layoutData });
		console.log('Layout data saved successfully.');
	}
	catch (error) {
		
		console.error("Error saving user layout:", error);
		throw error;
	}
};

/**
* Delete Data
*/
export const deleteLayoutData = async (layoutId) => {
	
	await openDatabase();
	try {
		await layoutDB.deleteData('LayoutData', layoutId);
		console.log('Layout data deleted successfully!');
	}
	catch (error) {
		
		console.error("Error clearing user layouts:", error);
		throw error;
	}
};

// Additional operations as needed...

Wanting to save the form data within the indexedDB, should I save into the indexedDB from saveBlockData or within the modal .js?