<script>
	import Dialog from "../ui/Dialog.svelte";
	import TableCudButtons from "../shorts/TableCUDButtons.svelte";
	import Button from "../ui/Button.svelte";
	import Table from "../table/Table.svelte";
	import Field from "../form/Field.svelte";
	import TextInput from "../form/TextInput.svelte";
	import Search from "../ui/Search.svelte";

	export let is_item_dialog_open = false;
	export let is_dialog_item_add = false;

	export let cur_dialog_name = "__example__";
	export let current_table;

	/** @type {any} */
	export let current_item;

	export let query;

	export let db;

	export let toggle_add_dialog = () => {};
	export let open_item_edit = (/** @type {any} */ item) => {};

	export let sql_insert_short = async (
		/** @type {any} */ arg1,
		/** @type {any} */ arg2,
	) => {};
	export let sql_update_short = async (
		/** @type {any} */ arg1,
		/** @type {any} */ arg2,
	) => {};
	export let sql_delete_short = () => {};

	export let second_col_name = "name";
	export let columns = ["id", "name"];
	export let columns_display = columns;

	// export let is_searching = false;
	export let is_searching = false;

	let search_query_result = "";
</script>

<Dialog
	bind:is_open={is_item_dialog_open}
	on_close={() => {
		is_dialog_item_add = false;
	}}
	name={cur_dialog_name}
	let:form
>
	{#if !is_dialog_item_add}
		<h1>{columns_display[0]} {current_item.id}</h1>
	{/if}

	<Field name={columns_display[1]}>
		<slot name="second_value_input">
			<TextInput bind:value={current_item[second_col_name]}></TextInput>
		</slot>
	</Field>

	<TableCudButtons
		{form}
		bind:is_dialog_item_add
		on_add={async () => {
			await sql_insert_short(current_table, [second_col_name]);
		}}
		on_save={async () => {
			await sql_update_short(current_table, [second_col_name]);
		}}
		on_delete={sql_delete_short}
	></TableCudButtons>
</Dialog>

<div class="m-2 flex space-x-2">
	<Button
		is_visible={!is_searching}
		on_click={() => {
			current_item = {
				id: 0,
			};
			current_item[second_col_name] = "";
			toggle_add_dialog();
		}}
	>
		Добавить
	</Button>

	<Search
		bind:is_searching
		bind:current_item
		bind:search_query_result
		{columns}
		{current_table}
	></Search>
	<!-- <Button -->
	<!--   on_click={async () => { -->
	<!--     await export_csv(data); -->
	<!--   }} -->
	<!-- > -->
	<!--   CSV -->
	<!-- </Button> -->
</div>

<Table
	bind:is_searching
	search_query={db.select(search_query_result)}
	{open_item_edit}
	{query}
	{columns}
	{columns_display}
></Table>
