import * as gql from "railbird-gql";
import { useCallback, useState } from "react";
// @ts-ignore
import { useCameraPermission } from "react-native-vision-camera";
import { showAlert } from "../../lib/alert-messages";

interface VideoFlowInputParams {
	sessionName?: string;
	gameType: string;
	tableSize: string;
	videoId?: number;
}

export const useVideoDetails = ({ mode, videoId, params, navigation }) => {
	const { hasPermission, requestPermission } = useCameraPermission();

	// Initial state setup
	const initialState = mode === "save-video" && params ? params : {};

	// Session name input
	// Should session name be required?
	const [sessionName, setSessionName] = useState<string>(
		initialState.sessionName || "",
	);

	// Game type dropdown
	const [gameTypeOpen, setGameTypeOpen] = useState<boolean>(false);
	const [gameType, setGameType] = useState<string | null>(
		initialState.gameType || null,
	);
	const [gameTypes, setGameTypes] = useState([
		{ label: "Free Play", value: "freePlay" },
		{ label: "Straight Pool", value: "straightPool" },
		{ label: "Nine Ball", value: "nineBall" },
	]);

	// Table size dropdown
	const [tableSizeOpen, setTableSizeOpen] = useState<boolean>(false);
	const [tableSize, setTableSize] = useState<string>(
		initialState.tableSize || "",
	);
	const [tableSizes, setTableSizes] = useState([
		{ label: `9'`, value: "nineFoot" },
		{ label: `8'`, value: "eightFoot" },
		{ label: "7", value: "sevenFoot" },
	]);

	// Toggle dropdowns mutually exclusive
	const onGameTypeOpen = useCallback(() => setTableSizeOpen(false), []);
	const onTableSizeOpen = useCallback(() => setGameTypeOpen(false), []);

	// GraphQL Mutation
	const [TerminateUploadStream, { loading, error }] =
		gql.useTerminateUploadStreamMutation();

	const handleSubmit = async () => {
		if (mode === "start-video" && !hasPermission) {
			requestPermission();
			return showAlert("camera");
		}

		if (mode === "start-video") {
			const params: VideoFlowInputParams = { sessionName, gameType, tableSize };
			navigation.push("Camera", params);
		} else {
			try {
				await TerminateUploadStream({
					variables: { videoId, videoName: sessionName, tableSize, gameType },
				});
				navigation.push("Tabs");
			} catch (err) {
				showAlert("terminateUpload");
			}
		}
	};

	return {
		sessionName,
		setSessionName,
		gameType,
		setGameType,
		gameTypeOpen,
		setGameTypeOpen,
		gameTypes,
		setGameTypes,
		onGameTypeOpen,
		tableSize,
		setTableSize,
		setTableSizes,
		tableSizeOpen,
		setTableSizeOpen,
		tableSizes,
		onTableSizeOpen,
		handleSubmit,
		loading,
		error,
	};
};
