"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import { useConvexAuth, useQuery } from "convex/react";
import type { DocumentTable } from "@/types/online-table";
import { deleteOnlineTable, getDocumentTable, saveOnlineTable } from "@/lib/online-table";
import { Loader2, Table as TableIcon, Maximize2, Trash2, RotateCw } from "lucide-react";
import { api } from "@/lib/convex/api";
import { isConvexEnabled } from "@/lib/convex/enabled";

interface CompactTablePreviewProps {
  tableId: string;
  onFullScreen: () => void;
  onDelete?: () => void;
  height?: number;
}

const useTableData = (tableId: string) => {
  const convexEnabled = isConvexEnabled();
  const { isAuthenticated } = useConvexAuth();
  const currentUser = useQuery(api.users.currentUser, convexEnabled && isAuthenticated ? {} : "skip");
  const userId =
    currentUser && typeof currentUser === "object" && typeof (currentUser as any)._id === "string"
      ? String((currentUser as any)._id)
      : "";
  const tableFromConvex = useQuery(
    api.tables.get,
    convexEnabled && userId && tableId ? { userId, tableId } : "skip",
  );

  const [table, setTable] = useState<DocumentTable | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [version, setVersion] = useState(0);

  const refresh = useCallback(() => {
    if (!convexEnabled) {
      setIsLoading(true);
      setVersion((prev) => prev + 1);
    }
  }, [convexEnabled]);

  useEffect(() => {
    if (convexEnabled) {
      if (tableFromConvex === undefined) {
        setIsLoading(true);
        return;
      }
      if (tableFromConvex === null) {
        setTable(null);
        setIsLoading(false);
        return;
      }
      setTable({ ...(tableFromConvex as unknown as DocumentTable), title: (tableFromConvex as any)?.title || "未命名表格" });
      setIsLoading(false);
      return;
    }

    let canceled = false;
    getDocumentTable(tableId)
      .then((data) => {
        if (!canceled) {
          setTable({ ...data, title: data.title || "未命名表格" });
        }
      })
      .catch((error) => {
        console.error("Failed to load table:", error);
        if (!canceled) {
          setTable(null);
        }
      })
      .finally(() => {
        if (!canceled) {
          setIsLoading(false);
        }
      });
    return () => {
      canceled = true;
    };
  }, [convexEnabled, tableFromConvex, tableId, version]);

  return { table, isLoading, refresh };
};

const CompactTablePreviewInner: React.FC<CompactTablePreviewProps> = ({
  tableId,
  onFullScreen,
  onDelete,
  height,
}) => {
  const { table, isLoading, refresh } = useTableData(tableId);
  const [iframeVersion, setIframeVersion] = useState(0);
  const [iframeLoading, setIframeLoading] = useState(true);
  const [isRenaming, setIsRenaming] = useState(false);
  const [renameValue, setRenameValue] = useState("");
  const [isSavingTitle, setIsSavingTitle] = useState(false);
  const fixedViewerHeight = 320; // 默认视窗高度
  const minEmbedHeight = 260;
  const maxEmbedHeight = 440;
  const rowHeight = 26; // 预估单行高度，便于动态收缩高度

  const iframeSrc = useMemo(
    () => `/tables/${tableId}/view?embed=1&v=${iframeVersion}`,
    [tableId, iframeVersion],
  );

  useEffect(() => {
    const handleSaved = (event: Event) => {
      const detail = (event as CustomEvent<{ tableId?: string }>).detail;
      if (detail?.tableId === tableId) {
        refresh();
      }
    };
    const handleDeleted = (event: Event) => {
      const detail = (event as CustomEvent<{ tableId?: string }>).detail;
      if (detail?.tableId === tableId) {
        refresh();
      }
    };
    window.addEventListener("online-table-saved", handleSaved as EventListener);
    window.addEventListener("online-table-deleted", handleDeleted as EventListener);
    return () => {
      window.removeEventListener("online-table-saved", handleSaved as EventListener);
      window.removeEventListener("online-table-deleted", handleDeleted as EventListener);
    };
  }, [refresh, tableId]);

  useEffect(() => {
    if (table?.title !== undefined) {
      setRenameValue(table.title ?? "");
    }
  }, [table?.title]);

  const suppressEditorEvents = useCallback((event: React.MouseEvent) => {
    event.stopPropagation();
  }, []);

  const handleDeleteTable = useCallback(async () => {
    const confirmed = window.confirm("删除表格将同步移除在线表格记录，确认继续？");
    if (!confirmed) return;
    try {
      await deleteOnlineTable(tableId);
      window.dispatchEvent(new CustomEvent("online-table-deleted", { detail: { tableId } }));
      onDelete?.();
    } catch (error) {
      console.error("删除表格失败", error);
      window.alert("删除失败，请稍后重试");
    }
  }, [onDelete, tableId]);

  const handleRefresh = useCallback(() => {
    setIframeVersion((value) => value + 1);
    setIframeLoading(true);
    refresh();
  }, [refresh]);
  const estimatedRows = useMemo(() => {
    const rowsBySnapshot =
      Array.isArray(table?.snapshot?.rows) && table.snapshot?.rows
        ? table.snapshot.rows.length
        : 0;
    const celldata = table?.snapshot?.luckysheet?.[0]?.celldata;
    const rowsByCells =
      Array.isArray(celldata) && celldata.length > 0
        ? Math.max(
            ...celldata.map((cell) =>
              typeof cell?.r === "number" ? cell.r : -1,
            ),
          ) + 1
        : 0;
    const fallbackRows = 10;
    return Math.max(rowsBySnapshot, rowsByCells, fallbackRows);
  }, [table?.snapshot]);

  const clampHeight = useCallback(
    (value: number) => Math.min(maxEmbedHeight, Math.max(minEmbedHeight, value)),
    [maxEmbedHeight, minEmbedHeight],
  );
  const autoHeight = clampHeight(estimatedRows * rowHeight);
  const effectiveHeight = clampHeight(height ?? autoHeight ?? fixedViewerHeight);
  const effectiveWidth: number | string = "100%";

  const handleRenameSubmit = useCallback(async () => {
    if (!table) {
      return;
    }
    const nextTitle = (renameValue || "").trim() || "未命名表格";
    if (nextTitle === table.title) {
      setIsRenaming(false);
      return;
    }
    setIsSavingTitle(true);
    try {
      const updated = await saveOnlineTable(tableId, { title: nextTitle });
      const finalTitle = updated.title ?? nextTitle;
      window.dispatchEvent(new CustomEvent("online-table-saved", { detail: { tableId } }));
      refresh();
      setRenameValue(finalTitle);
    } catch (error) {
      console.error("重命名表格失败", error);
      setRenameValue(table.title ?? "");
    } finally {
      setIsRenaming(false);
      setIsSavingTitle(false);
    }
  }, [refresh, renameValue, table, tableId]);

  if (isLoading) {
    return (
      <div className="flex h-20 items-center justify-center rounded-md border border-dashed bg-gray-50">
        <Loader2 className="h-5 w-5 animate-spin text-gray-400" />
      </div>
    );
  }

  if (!table) {
    return (
      <div className="flex h-24 items-center justify-between rounded-md border border-red-200 bg-red-50 px-4 py-2 text-red-600">
        <div className="flex items-center gap-2 text-sm">
          <TableIcon className="h-5 w-5" />
          <span>表格加载失败或不存在</span>
        </div>
        <button
          type="button"
          onClick={handleRefresh}
          className="flex items-center gap-2 rounded-md border border-red-200 px-3 py-1 text-xs font-medium"
        >
          <RotateCw className="h-4 w-4" />
          重试
        </button>
      </div>
    );
  }

  return (
    <div
      className="w-full"
      onDoubleClick={onFullScreen}
      contentEditable={false}
      onMouseDown={suppressEditorEvents}
      onMouseUp={suppressEditorEvents}
      onMouseMove={suppressEditorEvents}
    >
      <div
        className="relative overflow-hidden rounded-2xl border border-gray-100 bg-white/90 shadow-[0_10px_36px_rgba(15,23,42,0.05)] transition-all hover:shadow-[0_14px_44px_rgba(15,23,42,0.08)]"
        style={{
          width: effectiveWidth,
          maxWidth: "100%",
          marginLeft: "auto",
          marginRight: "auto",
          overflowX: "hidden",
        }}
      >
        <div className="flex items-center justify-between border-b border-gray-100 bg-white/80 px-4 py-2 backdrop-blur-sm">
          <div className="flex flex-col">
            {isRenaming ? (
              <input
                autoFocus
                className="w-48 rounded border border-gray-200 px-2 py-1 text-sm font-semibold text-gray-700 focus:border-emerald-500 focus:outline-none"
                value={renameValue}
                onChange={(e) => setRenameValue(e.target.value)}
                onBlur={handleRenameSubmit}
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    e.preventDefault();
                    void handleRenameSubmit();
                  }
                  if (e.key === "Escape") {
                    e.preventDefault();
                    setRenameValue(table.title ?? "");
                    setIsRenaming(false);
                  }
                }}
              />
            ) : (
              <button
                type="button"
                className="flex items-center gap-2 text-left text-sm font-semibold text-gray-700 hover:text-emerald-600"
                title="点击重命名表格"
                onClick={() => setIsRenaming(true)}
              >
                <span className="truncate max-w-xs">{table.title}</span>
                {isSavingTitle && <Loader2 className="h-3.5 w-3.5 animate-spin text-gray-400" />}
              </button>
            )}
            <p className="text-xs text-gray-400">嵌入视图 · 双击进入全屏编辑</p>
          </div>
          <div className="flex items-center gap-1">
            <button
              onClick={handleRefresh}
              className="rounded-md p-1.5 text-gray-400 ring-offset-white transition-colors hover:text-gray-600 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400"
              title="刷新嵌入视图"
              type="button"
            >
              <RotateCw className="h-4 w-4" />
            </button>
            <button
              onClick={handleDeleteTable}
              className="rounded-md p-1.5 text-gray-400 ring-offset-white transition-colors hover:text-red-500 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500"
              title="删除表格"
              type="button"
            >
              <Trash2 className="h-4 w-4" />
            </button>
            <button
              onClick={onFullScreen}
              className="rounded-md p-1.5 text-gray-400 ring-offset-white transition-colors hover:text-blue-500 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
              title="进入全屏编辑"
              type="button"
            >
              <Maximize2 className="h-4 w-4" />
            </button>
          </div>
        </div>

        <div
          className="relative w-full overflow-hidden bg-white select-none px-4 pb-4 pt-3"
          style={{ height: effectiveHeight, minHeight: minEmbedHeight }}
        >
          <div className="relative h-full w-full overflow-hidden rounded-xl border border-gray-100 bg-white">
            <iframe
              key={`${tableId}-${iframeVersion}`}
              src={iframeSrc}
              title={`online-table-${tableId}`}
              className="block h-full w-full border-0"
              loading="lazy"
              onLoad={() => setIframeLoading(false)}
              allow="clipboard-read; clipboard-write"
            />
          </div>
          {iframeLoading && (
            <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 rounded-xl bg-white/90">
              <Loader2 className="h-5 w-5 animate-spin text-gray-500" />
              <span className="text-xs text-gray-500">正在载入 Luckysheet 视图...</span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const CompactTablePreview: React.FC<CompactTablePreviewProps> = (props) => (
  <CompactTablePreviewInner key={props.tableId} {...props} />
);

export default CompactTablePreview;
