import throttle from "lodash/throttle";
import { useCallback, useEffect, useState } from "react";
import { TouchableOpacity, View } from "react-native";
import { StyledImage, StyledText } from "..";
import { sendAsAnalyticsEvent } from "../../../App/common/hooks/useAnalyticsEvent";
import {
  Cell as CellData,
  CellProps,
  Column,
  ColumnsProps,
  Row,
  RowsProps,
  TableWidgetProps,
} from "../../../App/common/interface/widgets/widgetData";
import { styles } from "./TableWidgetStyles";

const Cell = ({
  widgetData,
  cell,
  index,
  handleClick,
  handleActions,
}: CellProps) => {
  useEffect(() => {
    cell?.analyticEvents?.onViewEvent &&
      sendAsAnalyticsEvent(cell?.analyticEvents?.onViewEvent);
  }, []);
  const throttledHandleActions = useCallback(
    throttle(() => handleActions(null, cell?.action), 700, {
      leading: true,
      trailing: false,
    }),
    [widgetData],
  );
  const cellAction = () => {
    throttledHandleActions();
  };
  const handleTableCellClick = () => {
    if (cell?.cta) {
      handleClick && handleClick(cell?.cta);
    } else if (cell?.action) {
      cellAction();
    }
  };
  return (
    <TouchableOpacity
      style={[
        styles.cell,
        widgetData?.columns?.[index]?.columnStyle,
        cell?.cellStyle,
      ]}
      onPress={handleTableCellClick}
      activeOpacity={1}
    >
      {cell?.title?.text && (
        <StyledText key={`text-${index}`} textFieldData={cell?.title} />
      )}

      {cell?.image?.url && (
        <StyledImage key={`image-${index}`} imageFieldData={cell?.image} />
      )}
    </TouchableOpacity>
  );
};

const Rows = ({
  widgetData,
  rowsToDisplay,
  handleClick,
  handleActions,
}: RowsProps) => {
  return (
    <>
      {widgetData?.rows &&
        widgetData?.rows
          ?.slice(0, rowsToDisplay)
          ?.map((row: Row, index: number) => {
            return (
              <View style={styles.row} key={index}>
                {row?.cells?.map((cell: CellData, index: number) => (
                  <Cell
                    cell={cell}
                    index={index}
                    key={index}
                    widgetData={widgetData}
                    handleClick={handleClick}
                    handleActions={handleActions}
                  />
                ))}
              </View>
            );
          })}
    </>
  );
};
const Columns = ({ widgetData }: ColumnsProps) => {
  return (
    <View style={[styles.row]}>
      {widgetData?.columns &&
        widgetData?.columns?.map((column: Column, index: number) => {
          return (
            <View
              style={[styles.cell, styles.header, column?.columnStyle]}
              key={index}
            >
              {column?.image?.url && (
                <StyledImage imageFieldData={column?.image} />
              )}
              {column?.subImage?.url && (
                <StyledImage imageFieldData={column?.subImage} />
              )}
              {column?.title?.text && (
                <StyledText textFieldData={column?.title} />
              )}
              {column?.subtitle?.text && (
                <StyledText textFieldData={column?.subtitle} />
              )}
            </View>
          );
        })}
    </View>
  );
};

const Table = ({
  widgetData,
  handleClick,
  handleActions,
}: TableWidgetProps) => {
  const [rowsToDisplay, setRowsToDisplay] = useState<number | undefined>(
    widgetData?.rowsToDisplay || widgetData?.rows?.length,
  );

  const handleSelect = () => {
    setRowsToDisplay(widgetData?.rows?.length);
    widgetData?.viewButton?.cta?.analyticsEventProperties &&
      sendAsAnalyticsEvent(
        widgetData?.viewButton?.cta?.analyticsEventProperties,
      );
  };

  return (
    <>
      <Columns widgetData={widgetData} />
      <Rows
        widgetData={widgetData}
        rowsToDisplay={rowsToDisplay}
        handleClick={handleClick}
        handleActions={handleActions}
      />
      {rowsToDisplay !== widgetData?.rows?.length &&
        widgetData.viewButton?.text && (
          <TouchableOpacity onPress={handleSelect} activeOpacity={1}>
            <StyledText textFieldData={widgetData?.viewButton} />
          </TouchableOpacity>
        )}
    </>
  );
};

export default Table;
