import React, { useMemo, useState } from "react";
import { TouchableOpacity } from "react-native";

import { Link } from "../Link";
import { View } from "../View";
import styles from "./styles";

type TableRowProps = {
  children: React.ReactNode;
  clickHandler?: (rowData: any) => void;
  rowData: any;
  rowLinkProps?: (rowData: any) => Record<string, unknown>;
  rowProps: any;
};

const TableRow = ({
  rowData,
  rowLinkProps,
  rowProps,
  clickHandler,
  children,
}: TableRowProps) => {
  const { style, ...props } = rowProps;
  const [hover, setHover] = useState(false);
  const onMouseEnter = () => {
    if (!hover) {
      setHover(true);
    }
  };
  const onMouseLeave = () => {
    if (hover) {
      setHover(false);
    }
  };
  const linkProps = useMemo(
    () => (rowLinkProps ? rowLinkProps(rowData) : null),
    [rowData]
  );

  const Row = (
    <View
      style={[style, styles.tr, hover && styles.rowHover]}
      {...props}
      onMouseEnter={linkProps || clickHandler ? onMouseEnter : null}
      onMouseLeave={linkProps || clickHandler ? onMouseLeave : null}
    >
      {children}
    </View>
  );

  if (linkProps) {
    return <Link {...linkProps}>{Row}</Link>;
  }

  if (clickHandler) {
    return (
      // @ts-ignore
      <TouchableOpacity
        onPressIn={() => {
          clickHandler(rowData);
        }}
      >
        {Row}
      </TouchableOpacity>
    );
  }
  return Row;
};

export default TableRow;
