import React, { useMemo, useEffect } from "react";
import { TouchableWithoutFeedback } from "react-native";
import { usePagination, useTable } from "react-table";

import { default as useMazloPagination } from "../../hooks/usePagination";
import { Checkbox } from "../Checkbox";
import { Image } from "../Image";
import { Pagination } from "../Pagination";
import { Text } from "../Text";
import { View } from "../View";
import styles from "./styles";

type Image = {
  id: string;
  source: {
    uri: string;
  };
  title: string;
};

type ImageItemProps = {
  image: Image;
  marginHorizontal: number;
  marginVertical: number;
  selected: boolean;
  size: number;
  onSelect: () => void;
};

const ImageItem = ({
  image: {
    source: { uri },
    title,
  },
  marginHorizontal,
  marginVertical,
  selected,
  size,
  onSelect,
}: ImageItemProps) => {
  return (
    <TouchableWithoutFeedback onPress={onSelect}>
      <View
        style={[
          styles.itemContainer,
          {
            marginHorizontal,
            marginVertical,
            width: size,
          },
        ]}
      >
        <View
          style={[
            styles.imageContainer,
            { height: size },
            selected && styles.imageContainerSelected,
          ]}
        >
          <Image
            background
            accessibilityRole="image"
            style={[styles.image, selected && styles.imageSelected]}
            source={{ uri }}
            resizeMode="cover"
          />
        </View>
        <Text style={styles.title} numberOfLines={1}>
          {title}
        </Text>
        <Checkbox
          style={styles.checkbox}
          value={selected}
          onChange={onSelect}
        />
      </View>
    </TouchableWithoutFeedback>
  );
};

type Props = {
  count?: number;
  data: Image[];
  total?: number;
  selectedPageIndex?: number;
  imageSize?: number;
  selectedImages: { [id: string]: any };
  onAdd?: () => void;
  onSelect: (image: Image) => void;
  onPageChange?: (pageIndex: number) => void;
};

const ImageGrid = ({
  count,
  selectedPageIndex = 0,
  data,
  imageSize = 200,
  selectedImages,
  total = data ? data.length : count,
  onPageChange,
  onSelect,
}: Props) => {
  const columns = useMemo(() => [{ accessor: "image" }], []);
  const marginHorizontal = 0.11 * imageSize;
  const marginVertical = 0.06 * imageSize;
  const pageSize = count || data.length || 1;
  const { onPageChange: onMazloPagination } = useMazloPagination();
  const {
    prepareRow,
    page,
    pageCount,
    gotoPage,
    state: { pageIndex },
  } = useTable(
    {
      columns,
      data,
      manualPagination: true,
      pageCount: Math.ceil(total / count),
      initialState: { pageIndex: selectedPageIndex, pageSize },
    },
    usePagination
  );
  useEffect(() => {
    if (onPageChange) {
      onPageChange(pageIndex);
    } else {
      onMazloPagination(pageIndex);
    }
  }, [pageIndex]);

  return (
    <View>
      <View
        // @ts-ignore
        accessibilityRole="grid"
        style={[
          styles.container,
          {
            marginHorizontal: -marginHorizontal,
            marginTop: -marginVertical,
            marginBottom: marginVertical,
          },
        ]}
      >
        {page.map((row) => {
          prepareRow(row);
          const image = row.original;
          return (
            <ImageItem
              key={image.id}
              selected={selectedImages[image.id]}
              image={image}
              marginHorizontal={marginHorizontal}
              marginVertical={marginVertical}
              size={imageSize}
              onSelect={() => onSelect(image)}
            />
          );
        })}
      </View>
      <Pagination
        count={pageCount}
        selected={selectedPageIndex}
        rangeSize={4}
        onPageChange={(i) => {
          gotoPage(i);
        }}
      />
    </View>
  );
};

export default ImageGrid;
