"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import { DocumentTable, TableColumn, TableRowData } from "@/types/online-table";
import {
  DEFAULT_TABLE_COLUMNS,
  DEFAULT_TABLE_ROWS,
  deleteOnlineTable,
  getDocumentTable,
} from "@/lib/online-table";
import { Loader2, Table, Maximize2, Trash2 } from "lucide-react";

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

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

  const refresh = useCallback(() => setVersion((prev) => prev + 1), []);

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

  return { table, isLoading, refresh };
};

const pickCellDisplayValue = (cell: any) => {
  if (!cell) return undefined;
  if (cell.m !== undefined && cell.m !== null) return cell.m;
  if (cell.v?.m !== undefined && cell.v?.m !== null) return cell.v.m;
  if (cell.v?.v !== undefined && cell.v?.v !== null) return cell.v.v;
  if (cell.v !== undefined && cell.v !== null && typeof cell.v !== "object") return cell.v;
  if (cell.w !== undefined && cell.w !== null) return cell.w;
  return undefined;
};

const deriveRowsFromLuckysheet = (luckysheetData: any, columns: TableColumn[]): TableRowData[] => {
  const sheets = Array.isArray(luckysheetData) ? luckysheetData : [];
  const sheet = sheets[0];
  if (!sheet) return [];

  const columnIds = columns.length > 0
    ? columns.map((col) => col.id)
    : Array.from({ length: DEFAULT_TABLE_COLUMNS }, (_, index) => `col${index + 1}`);

  const rows: TableRowData[] = [];
  const dataGrid = Array.isArray(sheet.data) ? sheet.data : [];

  dataGrid.forEach((rowData: any[], rowIndex: number) => {
    if (!Array.isArray(rowData)) return;
    const row: TableRowData = {};
    let hasValue = false;
    columnIds.forEach((colId, colIndex) => {
      const value = pickCellDisplayValue(rowData[colIndex]);
      if (value !== undefined && value !== null && value !== "") {
        row[colId] = value;
        hasValue = true;
      }
    });
    if (hasValue) rows.push(row);
  });

  if (rows.length === 0 && Array.isArray(sheet.celldata)) {
    const map = new Map<number, TableRowData>();
    sheet.celldata.forEach((cell: { r: number; c: number; v: unknown }) => {
      const value = pickCellDisplayValue(cell?.v ?? cell);
      if (value === undefined || value === null || value === "") return;
      const existing = map.get(cell.r) ?? {};
      existing[columnIds[cell.c] ?? `col${cell.c + 1}`] = value;
      map.set(cell.r, existing);
    });
    Array.from(map.entries())
      .sort(([a], [b]) => a - b)
      .forEach(([, row]) => rows.push(row));
  }

  return rows;
};

const renderCellContent = (column: TableColumn, value: any) => {
  if (value === undefined || value === null || value === "") {
    return "";
  }
  if (column.type === "select") {
    const option = column.options?.find((opt) => opt.value === value);
    if (option) {
      return (
        <span className="px-2 py-0.5 text-xs font-medium rounded-full" style={{ backgroundColor: option.color, color: "white" }}>
          {value}
        </span>
      );
    }
  }
  return String(value);
};

const CompactTablePreview: React.FC<CompactTablePreviewProps> = ({ tableId, onFullScreen, onDelete }) => {
  const { table, isLoading, refresh } = useTableData(tableId);
  const [visibleRows, setVisibleRows] = useState(5);
  const [visibleCols, setVisibleCols] = useState(5);

  const schemaColumns = useMemo(
    () => Array.isArray(table?.schema?.columns) ? table!.schema.columns : [],
    [table],
  );

  const rows: TableRowData[] = useMemo(() => {
    if (!table) return [];
    if (Array.isArray(table.snapshot?.rows) && table.snapshot.rows.length > 0) {
      return table.snapshot.rows as TableRowData[];
    }
    if ((table.snapshot as { luckysheet?: unknown })?.luckysheet) {
      return deriveRowsFromLuckysheet(
        (table.snapshot as { luckysheet?: unknown }).luckysheet,
        schemaColumns,
      );
    }
    return [];
  }, [schemaColumns, table]);

  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]);

  const hasData = rows.length > 0 && schemaColumns.length > 0;

  const totalRowsAvailable = hasData ? rows.length : DEFAULT_TABLE_ROWS;
  const totalColsAvailable = hasData ? schemaColumns.length : DEFAULT_TABLE_COLUMNS;

  useEffect(() => {
    const maxRows = Math.max(5, totalRowsAvailable);
    const maxCols = Math.max(5, totalColsAvailable);
    if (visibleRows > maxRows) {
      setVisibleRows(maxRows);
    } else if (visibleRows < 5) {
      setVisibleRows(5);
    }
    if (visibleCols > maxCols) {
      setVisibleCols(maxCols);
    } else if (visibleCols < 5) {
      setVisibleCols(5);
    }
  }, [totalRowsAvailable, totalColsAvailable, visibleRows, visibleCols]);

  const columns = useMemo(() => {
    if (schemaColumns.length > 0) {
      return schemaColumns.slice(0, visibleCols);
    }
    const placeholderCount = Math.max(visibleCols, 5);
    return Array.from({ length: placeholderCount }, (_, index) => ({
      id: `placeholder_col_${index}`,
      name: "",
      type: "text" as const,
      width: 100,
    }));
  }, [schemaColumns, visibleCols]);

  const rowsToDisplay = useMemo(() => {
    if (rows.length > 0) {
      return rows.slice(0, visibleRows);
    }
    const placeholderCount = Math.max(visibleRows, 5);
    return Array.from({ length: placeholderCount }, (_, index) => ({ id: `placeholder_row_${index}` }));
  }, [rows, visibleRows]);

  const headerCells = useMemo(() => {
    const cells = [
      <th key="row-actions" className="w-8" aria-label="行操作列" />,
    ];
    columns.forEach((col) => {
      cells.push(
        <th
          key={col.id}
          style={{ width: col.width ?? 100 }}
          className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap relative group"
        >
          {col.name}
        </th>,
      );
    });
    return cells;
  }, [columns]);

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

  const handleDeleteTable = useCallback(async () => {
    const confirmed = window.confirm("删除表格将同步移除 Supabase 记录，确认继续？");
    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]);

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

  if (!table) {
    return (
      <div className="flex items-center justify-center h-20 bg-red-50 border border-red-300 rounded-md text-red-700">
        <Table className="h-5 w-5 mr-2" />
        表格加载失败或不存在。
      </div>
    );
  }

  return (
    <div
      className="relative w-full p-1 border border-gray-200 rounded-md transition-shadow hover:shadow-md"
      onDoubleClick={onFullScreen}
      contentEditable={false}
      onMouseDown={suppressEditorEvents}
      onMouseUp={suppressEditorEvents}
      onMouseMove={suppressEditorEvents}
    >
      <div className="flex justify-between items-center px-2 py-1">
        <h3 className="text-sm font-semibold text-gray-700">{table.title}</h3>
        <div className="flex items-center space-x-1">
          <span className="text-[11px] text-gray-400">只读预览，双击进入全屏编辑</span>
          <button
            onClick={handleDeleteTable}
            className="p-1 text-gray-400 hover:text-red-500 transition-colors"
            title="删除表格"
          >
            <Trash2 className="h-4 w-4" />
          </button>
          <button
            onClick={onFullScreen}
            className="p-1 text-gray-400 hover:text-blue-500 transition-colors"
            title="进入全屏编辑"
          >
            <Maximize2 className="h-4 w-4" />
          </button>
        </div>
      </div>

      <div className="overflow-x-auto">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-100">
            <tr>{headerCells}</tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {rowsToDisplay.map((row, index) => {
              const rowId = (row as { id?: string }).id || index;
              return (
                <tr
                  key={rowId}
                  className="hover:bg-gray-50 relative group cursor-pointer"
                  onClick={onFullScreen}
                >
                  <td className="w-8 p-0 text-center" />
                  {columns.map((col) => (
                    <td
                      key={col.id}
                      className="px-3 py-2 whitespace-nowrap text-sm text-gray-900 border-l border-gray-100 text-center align-middle min-w-[80px]"
                    >
                      {renderCellContent(col, (row as Record<string, unknown>)[col.id])}
                    </td>
                  ))}
                </tr>
              );
            })}
            {rows.length > rowsToDisplay.length && (
              <tr>
                <td colSpan={columns.length + 1} className="px-4 py-2 text-center text-xs text-gray-500 italic">
                  ... 更多 {rows.length - rowsToDisplay.length} 行数据，双击进入全屏查看
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
      <div className="flex items-center justify-end space-x-4 mt-2 text-xs text-gray-500">
        <label className="flex items-center space-x-2">
          <span>行数</span>
          <input
            type="range"
            min={5}
            max={Math.max(5, totalRowsAvailable)}
            value={visibleRows}
            onChange={(event) => setVisibleRows(Number(event.target.value))}
            className="h-1.5 w-28 accent-blue-500"
          />
          <span>{visibleRows}</span>
        </label>
        <label className="flex items-center space-x-2">
          <span>列数</span>
          <input
            type="range"
            min={5}
            max={Math.max(5, totalColsAvailable)}
            value={visibleCols}
            onChange={(event) => setVisibleCols(Number(event.target.value))}
            className="h-1.5 w-28 accent-blue-500"
          />
          <span>{visibleCols}</span>
        </label>
      </div>
    </div>
  );
};

export default CompactTablePreview;
