"use client";

import { useEffect, useMemo, useReducer, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import type { TChartQuery } from "@formbricks/types/analysis";
import { DatasetFieldsGate } from "@/modules/ee/analysis/charts/components/dataset-fields-gate";
import { DimensionsPanel } from "@/modules/ee/analysis/charts/components/dimensions-panel";
import { FiltersPanel } from "@/modules/ee/analysis/charts/components/filters-panel";
import { MatrixQuestionPicker } from "@/modules/ee/analysis/charts/components/matrix-question-picker";
import { MeasuresPanel } from "@/modules/ee/analysis/charts/components/measures-panel";
import { TimeDimensionPanel } from "@/modules/ee/analysis/charts/components/time-dimension-panel";
import { useChartQuery } from "@/modules/ee/analysis/charts/hooks/use-chart-query";
import { useDatasetChartFields } from "@/modules/ee/analysis/charts/hooks/use-dataset-chart-fields";
import { prepareQueryForChartType } from "@/modules/ee/analysis/charts/lib/big-number";
import {
  EMPTY_CHART_BUILDER_STATE,
  toAdoptedQueryJson,
  toComparableQueryJson,
} from "@/modules/ee/analysis/charts/lib/builder-query";
import { namesDatasetField } from "@/modules/ee/analysis/charts/lib/catalog-embedded-fields";
import { supportsTimeGrouping } from "@/modules/ee/analysis/charts/lib/chart-display";
import { createDefaultFilterRow } from "@/modules/ee/analysis/charts/lib/filter-conditions";
import {
  buildMatrixQuestionQuery,
  getMatrixQuestionLabel,
} from "@/modules/ee/analysis/charts/lib/matrix-pivot";
import {
  type ChartBuilderState,
  type FilterNode,
  type TimeDimensionConfig,
  buildCubeQuery,
  hasIncompleteFilterRow,
  parseQueryToState,
} from "@/modules/ee/analysis/lib/query-builder";
import type { AnalyticsResponse, TChartType } from "@/modules/ee/analysis/types/analysis";
import { AdvancedOptionToggle } from "@/modules/ui/components/advanced-option-toggle";

export interface ChartQueryState {
  isLoading: boolean;
  error: string | null;
  isPending: boolean;
  /**
   * The form differs from the query the preview holds: an edit still waiting to run, running, or run
   * and rejected. A rejected edit never reaches the preview, so this is the only place it shows.
   */
  hasUnadoptedEdit: boolean;
}

export const IDLE_CHART_QUERY_STATE: ChartQueryState = {
  isLoading: false,
  error: null,
  isPending: false,
  hasUnadoptedEdit: false,
};

interface AdvancedChartBuilderProps {
  workspaceId: string;
  chartType: TChartType;
  initialQuery?: TChartQuery;
  /**
   * The initial query arrives without rows (a preset), so run it once instead of treating it as
   * already executed the way a saved or AI-generated chart is.
   */
  runInitialQuery?: boolean;
  onChartGenerated?: (data: AnalyticsResponse) => void;
  onQueryStateChange?: (state: ChartQueryState) => void;
  feedbackDirectoryId: string | null;
}

const AUTO_RUN_DEBOUNCE_MS = 500;

const ACTION = {
  SET_MEASURES: "SET_MEASURES",
  SET_DIMENSIONS: "SET_DIMENSIONS",
  SET_FILTERS: "SET_FILTERS",
  SET_FILTER_LOGIC: "SET_FILTER_LOGIC",
  SET_TIME_DIMENSION: "SET_TIME_DIMENSION",
  INIT_FROM_QUERY: "INIT_FROM_QUERY",
} as const;

type Action =
  | { type: typeof ACTION.SET_MEASURES; payload: string[] }
  | { type: typeof ACTION.SET_DIMENSIONS; payload: string[] }
  | { type: typeof ACTION.SET_FILTERS; payload: FilterNode[] }
  | { type: typeof ACTION.SET_FILTER_LOGIC; payload: "and" | "or" }
  | { type: typeof ACTION.SET_TIME_DIMENSION; payload: TimeDimensionConfig | null }
  | { type: typeof ACTION.INIT_FROM_QUERY; payload: Partial<ChartBuilderState> };

const chartBuilderReducer = (state: ChartBuilderState, action: Action): ChartBuilderState => {
  switch (action.type) {
    case ACTION.SET_MEASURES:
      return { ...state, selectedMeasures: action.payload };
    case ACTION.SET_DIMENSIONS:
      return { ...state, selectedDimensions: action.payload };
    case ACTION.SET_FILTERS:
      return { ...state, filters: action.payload };
    case ACTION.SET_FILTER_LOGIC:
      return { ...state, filterLogic: action.payload };
    case ACTION.SET_TIME_DIMENSION:
      return { ...state, timeDimension: action.payload };
    case ACTION.INIT_FROM_QUERY:
      return { ...state, ...action.payload };
    default:
      return state;
  }
};

export function AdvancedChartBuilder({
  workspaceId,
  chartType,
  initialQuery,
  runInitialQuery = false,
  onChartGenerated,
  onQueryStateChange,
  feedbackDirectoryId,
}: Readonly<AdvancedChartBuilderProps>) {
  const { t } = useTranslation();
  const parsedInitial = initialQuery ? parseQueryToState(initialQuery) : null;

  const [state, dispatch] = useReducer(
    chartBuilderReducer,
    initialQuery ? { ...EMPTY_CHART_BUILDER_STATE, ...parsedInitial } : EMPTY_CHART_BUILDER_STATE
  );

  const { isLoading, error, runQuery } = useChartQuery(workspaceId, feedbackDirectoryId, initialQuery);
  const datasetFields = useDatasetChartFields(workspaceId, feedbackDirectoryId);
  const [isConfigDirty, setIsConfigDirty] = useState(false);
  const chartTypeRef = useRef(chartType);

  useEffect(() => {
    chartTypeRef.current = chartType;
  }, [chartType]);

  // The query handed in is the one the preview shows; it is handed in again after every successful run.
  const [adoptedQueryJson, setAdoptedQueryJson] = useState(() => toAdoptedQueryJson(initialQuery, chartType));

  const [dimensionsOpen, setDimensionsOpen] = useState(
    () => (parsedInitial?.selectedDimensions?.length ?? 0) > 0
  );
  const timeDimensionOpen = state.timeDimension != null;
  const filtersOpen = state.filters.length > 0;
  const timeGroupingSupported = supportsTimeGrouping(chartType);

  // Switching to a chart type that doesn't support time grouping (Big Number, Pie) drops the
  // granularity left over from a previous type, matching how sanitizeChartDisplay drops other
  // per-type display settings rather than saving them as dead values. The time dimension itself is
  // kept: with no granularity it is the chart's date-range filter (see TimeDimensionConfig), not a
  // grouping, and stripping it would silently widen the chart to all-time.
  useEffect(() => {
    if (!timeGroupingSupported && state.timeDimension?.granularity) {
      const { granularity: _granularity, ...rest } = state.timeDimension;
      dispatch({ type: ACTION.SET_TIME_DIMENSION, payload: rest });
    }
  }, [timeGroupingSupported, state.timeDimension]);

  // The executed query depends on the chart type as well as the form: a big number has nowhere to
  // put groups, so its query drops them (see prepareQueryForChartType). Switching the chart type
  // therefore changes the query and re-runs it, rather than re-rendering stale grouped rows.
  const currentQuery = useMemo(
    () => prepareQueryForChartType(buildCubeQuery(state), chartType),
    [state, chartType]
  );
  const currentQueryJson = JSON.stringify(currentQuery);
  const hasUnadoptedEdit = currentQueryJson !== adoptedQueryJson;

  useEffect(() => {
    onQueryStateChange?.({ isLoading, error, isPending: isConfigDirty || isLoading, hasUnadoptedEdit });
  }, [isLoading, error, isConfigDirty, hasUnadoptedEdit, onQueryStateChange]);

  // The dialog outlives the builder, so hand it back an idle state rather than this session's last one.
  const onQueryStateChangeRef = useRef(onQueryStateChange);
  useEffect(() => {
    onQueryStateChangeRef.current = onQueryStateChange;
  }, [onQueryStateChange]);
  useEffect(() => () => onQueryStateChangeRef.current?.(IDLE_CHART_QUERY_STATE), []);

  // The last query that was executed (or arrived pre-executed via initialQuery, e.g. from the
  // AI section or a saved chart). Auto-run only fires when the form drifts away from it.
  const lastRunQueryJsonRef = useRef<string | null>(
    initialQuery && !runInitialQuery ? toComparableQueryJson(initialQuery, chartType) : null
  );
  // Read by the effect below without re-running it; this effect is declared first, so it runs first.
  const runInitialQueryRef = useRef(runInitialQuery);
  useEffect(() => {
    runInitialQueryRef.current = runInitialQuery;
  }, [runInitialQuery]);

  const appliedInitialQueryRef = useRef<TChartQuery | null>(null);
  useEffect(() => {
    if (!initialQuery) return;
    if (appliedInitialQueryRef.current === initialQuery) return;
    appliedInitialQueryRef.current = initialQuery;
    const parsed = parseQueryToState(initialQuery);
    const initialQueryJson = toComparableQueryJson(initialQuery, chartType);
    lastRunQueryJsonRef.current = runInitialQueryRef.current ? null : initialQueryJson;
    setAdoptedQueryJson(toAdoptedQueryJson(initialQuery, chartType));
    dispatch({ type: ACTION.INIT_FROM_QUERY, payload: parsed });
    setDimensionsOpen((parsed.selectedDimensions?.length ?? 0) > 0);
    // chartType only feeds the baseline above; a later switch is caught by the guard and left to
    // drift detection, which is what re-runs the query for the new type.
  }, [initialQuery, chartType]);

  // Incomplete configs (no measure yet, half-filled filter row) are skipped silently instead of
  // surfacing validation toasts on every keystroke; the preview keeps its last valid state.
  const isConfigComplete = useMemo(() => {
    if (state.selectedMeasures.length === 0) return false;
    if (dimensionsOpen && state.selectedDimensions.length === 0) return false;
    // Walks into filter groups too, so a half-filled row nested in a group also holds the run back.
    return !hasIncompleteFilterRow(state.filters);
  }, [state, dimensionsOpen]);

  // Latest-value ref so the debounce timer is not reset by parent re-renders or
  // identity changes of runQuery/onChartGenerated.
  const executeQueryRef = useRef<() => void>(() => {});
  useEffect(() => {
    executeQueryRef.current = () => {
      lastRunQueryJsonRef.current = currentQueryJson;
      setIsConfigDirty(false);
      void runQuery(currentQuery, chartTypeRef.current).then((result) => {
        if (result) {
          onChartGenerated?.({ ...result, chartType: chartTypeRef.current });
        }
      });
    };
  });

  useEffect(() => {
    const hasDrift = currentQueryJson !== lastRunQueryJsonRef.current;
    setIsConfigDirty(hasDrift);

    if (!feedbackDirectoryId || !isConfigComplete || !hasDrift) return;

    const timeout = setTimeout(() => {
      executeQueryRef.current();
    }, AUTO_RUN_DEBOUNCE_MS);
    return () => clearTimeout(timeout);
  }, [currentQueryJson, isConfigComplete, feedbackDirectoryId]);

  const isMatrix = chartType === "matrix";
  // Picking a matrix question replaces the form with the matrix recipe — rows, columns, measure and
  // the question filter — and keeps the date range. The auto-run below then draws it.
  const applyMatrixQuestion = (label: string) => {
    const parsed = parseQueryToState(buildMatrixQuestionQuery(label, currentQuery.timeDimensions));
    dispatch({ type: ACTION.INIT_FROM_QUERY, payload: { ...EMPTY_CHART_BUILDER_STATE, ...parsed } });
    setDimensionsOpen(true);
  };

  return (
    <div className="space-y-2">
      {isMatrix && feedbackDirectoryId && (
        <MatrixQuestionPicker
          workspaceId={workspaceId}
          feedbackDirectoryId={feedbackDirectoryId}
          selectedLabel={getMatrixQuestionLabel(currentQuery)}
          onSelect={applyMatrixQuestion}
        />
      )}
      {/* Flat, like every other control in the rail: a filled box here read as a card inside a card. */}
      <MeasuresPanel
        hideTitle
        selectedMeasures={state.selectedMeasures}
        onMeasuresChange={(measures) => dispatch({ type: ACTION.SET_MEASURES, payload: measures })}
      />

      <AdvancedOptionToggle
        isChecked={filtersOpen}
        onToggle={() => {
          if (filtersOpen) {
            dispatch({ type: ACTION.SET_FILTERS, payload: [] });
          } else if (state.filters.length === 0) {
            dispatch({ type: ACTION.SET_FILTERS, payload: [createDefaultFilterRow()] });
          }
        }}
        htmlId="chart-filters-toggle"
        title={t("workspace.analysis.charts.filter_data")}
        description={t("workspace.analysis.charts.filters_toggle_description")}
        customContainerClass="mt-2 px-0"
        childrenContainerClass="flex-col gap-3 p-4"
        childBorder>
        <DatasetFieldsGate status={datasetFields} isNeeded={namesDatasetField(state.filters)}>
          <FiltersPanel
            workspaceId={workspaceId}
            feedbackDirectoryId={feedbackDirectoryId}
            datasetFields={datasetFields}
            filters={state.filters}
            filterLogic={state.filterLogic}
            onFiltersChange={(filters) => dispatch({ type: ACTION.SET_FILTERS, payload: filters })}
            onFilterLogicChange={(logic) => dispatch({ type: ACTION.SET_FILTER_LOGIC, payload: logic })}
          />
        </DatasetFieldsGate>
      </AdvancedOptionToggle>

      <AdvancedOptionToggle
        isChecked={dimensionsOpen}
        onToggle={(checked) => {
          setDimensionsOpen(checked);
          if (!checked) dispatch({ type: ACTION.SET_DIMENSIONS, payload: [] });
        }}
        htmlId="chart-dimensions-toggle"
        title={t("workspace.analysis.charts.group_data")}
        description={t("workspace.analysis.charts.dimensions_toggle_description")}
        customContainerClass="mt-2 px-0"
        childrenContainerClass="flex-col gap-3 p-4"
        childBorder>
        <DatasetFieldsGate status={datasetFields} isNeeded={namesDatasetField(state.selectedDimensions)}>
          <DimensionsPanel
            hideTitle
            isMatrix={isMatrix}
            embeddedFields={datasetFields.embeddedFields}
            workspaceId={workspaceId}
            // The preview's legend and headers name a renamed key only once it runs again.
            onEmbeddedFieldRenamed={() => {
              if (feedbackDirectoryId && isConfigComplete) executeQueryRef.current();
            }}
            selectedDimensions={state.selectedDimensions}
            onDimensionsChange={(dimensions) =>
              dispatch({ type: ACTION.SET_DIMENSIONS, payload: dimensions })
            }
          />
        </DatasetFieldsGate>
      </AdvancedOptionToggle>

      <AdvancedOptionToggle
        isChecked={timeDimensionOpen}
        onToggle={() => {
          if (timeDimensionOpen) dispatch({ type: ACTION.SET_TIME_DIMENSION, payload: null });
          else if (!state.timeDimension) {
            dispatch({
              type: ACTION.SET_TIME_DIMENSION,
              payload: {
                dimension: "FeedbackRecords.collectedAt",
                dateRange: "last 30 days",
              },
            });
          }
        }}
        htmlId="chart-time-dimension-toggle"
        title={
          timeGroupingSupported
            ? t("workspace.analysis.charts.time_dimension_title")
            : t("workspace.analysis.charts.time_dimension_title_range_only")
        }
        description={
          timeGroupingSupported
            ? t("workspace.analysis.charts.time_dimension_toggle_description")
            : t("workspace.analysis.charts.time_dimension_toggle_description_range_only")
        }
        customContainerClass="mt-2 px-0"
        childrenContainerClass="flex-col gap-3 p-4"
        childBorder>
        <TimeDimensionPanel
          hideTitle
          hideGranularity={!timeGroupingSupported}
          timeDimension={state.timeDimension}
          onTimeDimensionChange={(config) => dispatch({ type: ACTION.SET_TIME_DIMENSION, payload: config })}
        />
      </AdvancedOptionToggle>
    </div>
  );
}
