import { Chat } from "@/components/interaction-panel/chat";
import { createFileRoute } from "@tanstack/react-router";
import {
	SandpackCodeEditor,
	SandpackCodeViewer,
	SandpackFileExplorer,
	SandpackLayout,
	SandpackPreview,
	SandpackProvider,
} from "@codesandbox/sandpack-react";
import { useAccountStore } from "@/contexts/AccountContext";
import { observer } from "mobx-react-lite";

import { useState } from "react";

export const Route = createFileRoute("/interaction-panel/$id")({
	component: RouteComponent,
});

function RouteComponent() {
	return (
		<div className="flex h-full">
			<Chat />
			<Sandbox />
		</div>
	);
}

const Sandbox = observer(() => {
	const { isSandboxOpen } = useAccountStore();
	const [previewState, setPreviewState] = useState<"preview" | "code">(
		"preview",
	);
	const togglePreviewState = () => {
		setPreviewState((prev) => (prev === "preview" ? "code" : "preview"));
	};

	const files = {
		"/test.js": `const test = "content"`,
	};

	return (
		<div
			data-open={isSandboxOpen}
			className="w-0 border-l-1 p-0 px-2 pt-4 pb-2 font-work transition-all data-[open=true]:w-[40svw]"
		>
			<div className="flex h-full flex-col gap-4">
				<div className="flex min-h-[42px] flex-row items-center justify-between">
					<div className="flex h-full flex-row gap-0.5 rounded-lg bg-[#F5F5F5] p-0.5">
						<button
							type="button"
							data-active={previewState === "preview"}
							onClick={togglePreviewState}
							className="group inline-flex cursor-pointer flex-row items-center justify-between gap-1 rounded-lg px-4 transition-all data-[active=true]:bg-[#D6D6D6]"
						>
							<div className="mask-[url('/icons/Preview.svg')] size-6 bg-[#939393] bg-center bg-cover transition-colors group-data-[active=true]:bg-black" />
							Preview
						</button>
						<button
							type="button"
							data-active={previewState === "code"}
							onClick={togglePreviewState}
							className="group inline-flex cursor-pointer flex-row items-center justify-between gap-1 rounded-lg px-4 transition-all data-[active=true]:bg-[#D6D6D6]"
						>
							<div className="mask-[url('/icons/Code.svg')] size-6 bg-[#939393] bg-center bg-cover transition-colors group-data-[active=true]:bg-black" />
							Code
						</button>
					</div>
				</div>
				<SandpackProvider files={{}} theme="light" template="react">
					<SandpackLayout>
						<div
							data-active={previewState === "code"}
							className="hidden w-full data-[active=true]:block"
						>
							<SandpackFileExplorer style={{ height: "100svh" }} />
							<SandpackCodeEditor
								closableTabs
								showTabs
								style={{ height: "100svh" }}
							/>
						</div>
						<div
							data-active={previewState === "preview"}
							className="hidden w-full data-[active=true]:block"
						>
							<SandpackPreview style={{ height: "100svh" }} />
						</div>
					</SandpackLayout>
				</SandpackProvider>
			</div>
		</div>
	);
});
