import { useEffect, useMemo } from "react";
import { Container } from "@mantine/core";
import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
import { useAppStore } from "../store";
import { consumeLinkReturn } from "../features/qr/returnTo";
import { DeviceStrip }     from "../features/devices/DeviceStrip";
import { Composer }        from "../features/transfer/Composer";
import { ActivityFeed }    from "../features/transfer/ActivityFeed";
import { ClipboardPanel }  from "../features/clipboard/ClipboardPanel";
import { MessageList }     from "../features/messaging/MessageList";
import { startOutgoingTransfer } from "../features/transfer/transfer";
import { fileSource } from "../features/transfer/source";
import { sendMessage }     from "../features/messaging/messaging";
import { fetchClipboard, CLIPBOARD_MAX_BYTES } from "../features/clipboard/clipboard";
import { t } from "../i18n";
import { DynText } from "../ui/primitives";
import { toast } from "../ui/feedback";
import s from "./index.module.css";

export const Route = createFileRoute("/")({
    component: HomePage,
    beforeLoad: () =>
    {
        const { user, selfDeviceName } = useAppStore.getState();
        if (!user) { throw redirect({ to: "/login", search: { dev_user: undefined } }); }
        if (!selfDeviceName) { throw redirect({ to: "/setup" }); }
        // 批准页 redirect-back：登录后落到 "/" 时若有暂存的 /link 返回地址，弹回去。
        const back = consumeLinkReturn();
        if (back) { throw redirect({ to: back }); }
    },
});

// 在 hint 文案里直接展示;保留 import 以让 lib/clipboard 字节上限保持唯一来源。
void CLIPBOARD_MAX_BYTES;

function HomePage()
{
    const navigate         = useNavigate();
    const user             = useAppStore((s) => s.user);
    const sessionScope     = useAppStore((s) => s.sessionScope);
    const devices          = useAppStore((s) => s.devices);
    const selfDeviceName   = useAppStore((s) => s.selfDeviceName);
    const activeTransfers  = useAppStore((s) => s.activeTransfers);
    const history          = useAppStore((s) => s.history);
    const messages         = useAppStore((s) => s.messages);
    const clipboard        = useAppStore((s) => s.clipboard);
    const selectedDevice   = useAppStore((s) => s.selectedDevice);
    const selectedFile     = useAppStore((s) => s.selectedFile);
    const setSelectedDevice = useAppStore((s) => s.setSelectedDevice);
    const setSelectedFile   = useAppStore((s) => s.setSelectedFile);
    const removeMessage     = useAppStore((s) => s.removeMessage);
    const clearMessages     = useAppStore((s) => s.clearMessages);

    // 进页面拉一次最新（带 If-None-Match）。SSE 实时推送在 hub.ts 里处理。
    useEffect(() => { void fetchClipboard().catch(() => {}); }, []);

    const activeList = useMemo(() => Object.values(activeTransfers), [ activeTransfers ]);

    const handleSendFile = async () =>
    {
        if (!selectedDevice || !selectedFile) { return; }
        try
        {
            await startOutgoingTransfer(selectedDevice, fileSource(selectedFile));
            setSelectedFile(null);
        }
        catch (e)
        {
            toast.error("文件发送失败", e instanceof Error ? e.message : String(e));
        }
    };

    const handleSendMessage = async (text: string) =>
    {
        if (!selectedDevice) { throw new Error(t("home.cta.selectDevice")); }
        await sendMessage(selectedDevice, text);
    };

    // 拖文件直接到设备卡：跳过 composer，临时切换 target 后立刻发起。
    const handleDropFile = async (deviceName: string, file: File) =>
    {
        setSelectedDevice(deviceName);
        try { await startOutgoingTransfer(deviceName, fileSource(file)); }
        catch (e)
        {
            toast.error("文件发送失败", e instanceof Error ? e.message : String(e));
        }
    };

    return (
        <Container size="xl" py="lg">
            <div className={s.page}>
                <h1 className={s.greeting}>
                    <DynText>{t("home.greeting", { name: user?.name ?? "" })}</DynText>
                </h1>

                <DeviceStrip
                    devices={devices}
                    selfDeviceName={selfDeviceName}
                    selectedDevice={selectedDevice}
                    onSelect={setSelectedDevice}
                    onDropFile={handleDropFile}
                    // 受限访客不能授权新设备：不传 onLinkDevice，DeviceStrip 据此
                    // 隐藏「扫码登录新设备」入口（条件渲染已在组件内）。
                    onLinkDevice={
                        sessionScope === "guest"
                            ? undefined
                            : () => navigate({ to: "/link/scan" })
                    }
                />

                <div className={s.dualColumn}>
                    <div className={s.composeCol}>
                        <Composer
                            targetDevice={selectedDevice}
                            selectedFile={selectedFile}
                            onFileChange={setSelectedFile}
                            onSendFile={handleSendFile}
                            onSendMessage={handleSendMessage}
                        />
                    </div>
                    <div className={s.clipboardCol}>
                        <ClipboardPanel state={clipboard} selfDevice={selfDeviceName} />
                    </div>
                </div>

                <MessageList
                    messages={messages}
                    onDismiss={removeMessage}
                    onClearAll={clearMessages}
                />

                <ActivityFeed active={activeList} history={history} />
            </div>
        </Container>
    );
}
