import type { PlayerCharacter } from "@initiative/domain";
import { type RefObject, useImperativeHandle, useState } from "react";
import { usePlayerCharactersContext } from "../contexts/player-characters-context.js";
import { CreatePlayerModal } from "./create-player-modal.js";
import { PlayerManagement } from "./player-management.js";

export interface PlayerCharacterSectionHandle {
	openManagement: () => void;
}

export const PlayerCharacterSection = function PlayerCharacterSectionInner({
	ref,
}: {
	ref?: RefObject<PlayerCharacterSectionHandle | null>;
}) {
	const { characters, createCharacter, editCharacter, deleteCharacter } =
		usePlayerCharactersContext();

	const [managementOpen, setManagementOpen] = useState(false);
	const [createOpen, setCreateOpen] = useState(false);
	const [editingPlayer, setEditingPlayer] = useState<
		PlayerCharacter | undefined
	>();

	useImperativeHandle(ref, () => ({
		openManagement: () => setManagementOpen(true),
	}));

	return (
		<>
			<CreatePlayerModal
				open={createOpen}
				onClose={() => {
					setCreateOpen(false);
					setEditingPlayer(undefined);
					setManagementOpen(true);
				}}
				onSave={(name, ac, maxHp, color, icon, level) => {
					if (editingPlayer) {
						editCharacter(editingPlayer.id, {
							name,
							ac,
							maxHp,
							color: color ?? null,
							icon: icon ?? null,
							level: level ?? null,
						});
					} else {
						createCharacter(name, ac, maxHp, color, icon, level);
					}
				}}
				playerCharacter={editingPlayer}
			/>
			<PlayerManagement
				open={managementOpen}
				onClose={() => setManagementOpen(false)}
				characters={characters}
				onEdit={(pc) => {
					setEditingPlayer(pc);
					setCreateOpen(true);
					setManagementOpen(false);
				}}
				onDelete={(id) => deleteCharacter(id)}
				onCreate={() => {
					setEditingPlayer(undefined);
					setCreateOpen(true);
					setManagementOpen(false);
				}}
			/>
		</>
	);
};
