import type { Piece } from "backend/database";
import { PieceId } from "common";
import { FormEventHandler, useId, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import { client } from "../client";
import { useLoading } from "../loading";
import { Button } from "../styled/Button";
import { Input } from "../styled/Input";

export function Piece() {

	const id = PieceId(useParams().pieceId!);

	const { isLoading, error, data } = useLoading(() => client.piece.get({ query: { id } }));

	if (isLoading) {
		return (
			<div className="w-full h-full overflow-hidden flex items-center justify-center">
				<div>Ładowanie…</div>
			</div>
		);
	}

	return (
		<div className="p-4 overflow-y-auto flex flex-wrap gap-4">
			{error !== null ? (
				`Wystąpił błąd: ${error.value}`
			) : data[0] === undefined ? (
				"Utwór nie istnieje"
			) : (
				<PieceForm data={data[0]} />
			)}
		</div>
	);
}

namespace PieceForm {
	export interface Props {
		readonly data: Piece;
	}
}

function PieceForm(props: PieceForm.Props) {

	const [name, setName] = useState(props.data.name);
	const [composer, setComposer] = useState(props.data.composer ?? "");
	const [lyricist, setLyricist] = useState(props.data.lyricist ?? "");
	const [arranger, setArranger] = useState(props.data.arranger ?? "");

	const nameId = useId();
	const composerId = useId();
	const lyricistId = useId();
	const arrangerId = useId();

	const autoFocusRef = useRef<HTMLInputElement>(null);

	const onSubmit: FormEventHandler<HTMLFormElement> = async (e) => {
		e.preventDefault();
		if (props.data === null) {
			return;
		}

		const { error } = await client.piece({ pieceId: props.data.pieceId }).put({
			name,
			composer: composer.length > 0 ? composer : null,
			lyricist: lyricist.length > 0 ? lyricist : null,
			arranger: arranger.length > 0 ? arranger : null,
		});

		if (error) {
			console.error(error.value);
			return;
		}

		autoFocusRef.current?.focus();
	}

	return (
		<form className="p-2 flex flex-col gap-2 border rounded" onSubmit={onSubmit}>
			<label htmlFor={nameId}>Tytuł</label>
			<Input
				ref={autoFocusRef}
				id={nameId}
				type="text"
				value={name}
				required
				disabled={props.data === null}
				onChange={(e) => setName(e.target.value)}
			/>
			<label htmlFor={composerId}>Kompozytor</label>
			<Input
				id={composerId}
				type="text"
				value={composer}
				disabled={props.data === null}
				onChange={(e) => setComposer(e.target.value)}
			/>
			<label htmlFor={lyricistId}>Słowa</label>
			<Input
				id={lyricistId}
				type="text"
				value={lyricist}
				disabled={props.data === null}
				onChange={(e) => setLyricist(e.target.value)}
			/>
			<label htmlFor={arrangerId}>Opracowanie</label>
			<Input
				id={arrangerId}
				type="text"
				value={arranger}
				disabled={props.data === null}
				onChange={(e) => setArranger(e.target.value)}
			/>
			<Button type="submit" disabled={props.data === null}>
				Zapisz
			</Button>
		</form>
	);
}
