"use client";

import { DatabaseIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { TChartQuery } from "@formbricks/types/analysis";
import { ChartEmptyState } from "@/modules/ee/analysis/charts/components/chart-empty-state";
import { isChartResultEmpty } from "@/modules/ee/analysis/charts/lib/chart-emptiness";
import { formatCellValue } from "@/modules/ee/analysis/charts/lib/chart-utils";
import { isInjectedResponseBaseColumn } from "@/modules/ee/analysis/charts/lib/response-base";
import {
  formatCubeColumnHeader,
  getTranslatedDimensionValueLabel,
} from "@/modules/ee/analysis/lib/schema-definition";
import type { TChartDataRow } from "@/modules/ee/analysis/types/analysis";

const MAX_DISPLAY_ROWS = 50;
interface DataViewerProps {
  data: TChartDataRow[];
  /** value_id → default-language label map, present when the query groups by valueId. */
  optionLabels?: Record<string, string>;
  /** Matrix row field_id → statement map, present when the query groups by fieldId. */
  fieldLabels?: Record<string, string>;
  /** Embedded-data member → key name map, so those columns are headed by the key. */
  memberLabels?: Record<string, string>;
  /**
   * Drop the card, the heading and the fixed scroll height, and fill the parent instead. For a
   * dashboard widget, whose title bar already names the chart and whose body already scrolls —
   * keeping them there gives two scrollbars and the heading twice.
   */
  bare?: boolean;
  /** The chart's query, so a response base the server added (and the user never picked) stays out. */
  query?: TChartQuery;
}

export function DataViewer({
  data,
  optionLabels,
  fieldLabels,
  memberLabels,
  bare = false,
  query,
}: Readonly<DataViewerProps>) {
  const { t } = useTranslation();
  // The same empty state as the chart, so flipping a widget to its data says the same thing rather
  // than a lone "0" row (see isChartResultEmpty).
  if (
    !data ||
    data.length === 0 ||
    Object.keys(data[0]).length === 0 ||
    (query && isChartResultEmpty(data, query))
  ) {
    return <ChartEmptyState message={t("workspace.analysis.charts.no_data_available")} />;
  }

  const columns = Object.keys(data[0]).filter((key) => !query || !isInjectedResponseBaseColumn(key, query));
  const displayData = data.slice(0, MAX_DISPLAY_ROWS);

  const renderCellValue = (key: string, value: unknown): string => {
    if (key === "FeedbackRecords.valueId" && optionLabels && typeof value === "string") {
      return optionLabels[value] ?? value;
    }
    // A matrix row's field_id (`<elementId>__<rowId>`) reads as its statement, like the grid does.
    if (key === "FeedbackRecords.fieldId" && fieldLabels && typeof value === "string") {
      return fieldLabels[value] ?? value;
    }
    return getTranslatedDimensionValueLabel(key, value, t) ?? formatCellValue(value);
  };

  return (
    <div className={bare ? "flex h-full flex-col" : "rounded-lg border border-gray-200 bg-gray-50 p-4"}>
      {!bare && (
        <div className="mb-2 flex items-center gap-2">
          <DatabaseIcon className="size-4 text-gray-600" />
          <h4 className="text-sm font-semibold text-gray-900">{t("workspace.analysis.charts.chart_data")}</h4>
        </div>
      )}
      <div
        className={
          bare ? "min-h-0 flex-1 overflow-auto bg-white" : "max-h-64 overflow-auto rounded-sm bg-white"
        }>
        <table className="w-full text-xs">
          <thead className="bg-gray-100">
            <tr>
              {columns.map((key) => (
                <th
                  key={key}
                  scope="col"
                  className="border-b border-gray-200 px-3 py-2 text-left font-semibold">
                  {formatCubeColumnHeader(key, t, memberLabels)}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {displayData.map((row, index) => {
              const firstValue = Object.values(row)[0];
              const rowKey = firstValue ? String(firstValue) : `row-${index}`;
              return (
                <tr key={`data-row-${rowKey}-${index}`} className="border-b border-gray-100 hover:bg-gray-50">
                  {columns.map((key) => (
                    <td key={`cell-${key}-${rowKey}`} className="px-3 py-2">
                      {renderCellValue(key, row[key])}
                    </td>
                  ))}
                </tr>
              );
            })}
          </tbody>
        </table>
        {data.length > MAX_DISPLAY_ROWS && (
          <div className="px-3 py-2 text-xs text-gray-500">
            {t("workspace.analysis.charts.showing_first_n_of", {
              n: MAX_DISPLAY_ROWS,
              count: data.length,
            })}
          </div>
        )}
      </div>
    </div>
  );
}
