import React, { useEffect, useMemo, useState } from 'react';
import moment from 'moment';
import { Table } from '.';
import { TableRowActionType, TableBatchActionType } from './TableTypes';
import { Text } from '../Text';
import { Icon } from '../Icon';
import { IconButton } from '../IconButton';
import {
  SvgCheckboxMarkedCircle,
  SvgMinusCircle,
  SvgDelete,
  SvgCoins,
  SvgDeleteOutline,
} from '../../assets/images/icons';
import { IconCircled } from '../IconCircled';
import * as themeDefinitions from '../../styles/themeDefinitions';
import { Box } from '../Box';
import { DateInput } from '../DateInput';
import { TextInput } from '../TextInput';
import { Select } from '../Select';
import { ButtonSmall } from '../ButtonSmall';
import { NumberInput } from '../NumberInput';

export default {
  title: 'Table',
  component: Table,
};

const randomDate = (start: Date, end: Date) =>
  new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));

const initialData = (count: number) =>
  Array.from({ length: count }).map((e, i) => ({
    did: `0x0000000000${i}`,
    expiry: randomDate(new Date(), new Date(2022, 11, 20)),
    amount: (Math.random() * 1000 * i).toFixed(2),
    accredited: Math.random() >= 0.5,
    subRow: `Lorem ipsum dolor sitamet... ${i}`,
  }));

export const Default = () => {
  const [data, setData] = useState(initialData(15));
  const columns = useMemo(
    () => [
      {
        Header: 'Claims',
        columns: [
          {
            Header: 'Identity (DID)',
            accessor: 'did',
            footer: (index: number) =>
              index === 4 ? (
                <Text variant="b3" color="red.0">
                  This identity (DID) is invalid. Please remove or edit the
                  address to continue
                </Text>
              ) : null,
            editor: TextInput,
            editorProps: {
              blurOnEnterKeyPress: true,
            },
          },
          {
            Header: 'Expiry',
            accessor: 'expiry',
            formatter: (date: Date | null) =>
              date === null ? 'No expiry' : moment(date).format('MM/DD/YYYY'),
            editor: DateInput,
            editorProps: {
              noExpiryOption: true,
            },
          },
          {
            Header: 'Amount',
            accessor: 'amount',
            formatter: (amount: any) => Number(amount).toLocaleString(),
            editor: NumberInput,
            editorProps: {
              blurOnEnterKeyPress: true,
            },
          },
          {
            Header: 'Accredited',
            accessor: 'accredited',
            formatter: (state: any) =>
              state ? (
                <Icon
                  Asset={SvgCheckboxMarkedCircle}
                  width={22}
                  height={22}
                  color="success"
                />
              ) : (
                <Icon
                  Asset={SvgMinusCircle}
                  width={26}
                  height={26}
                  ml="-2px"
                  color="gray.3"
                />
              ),
            editor: Select,
            editorProps: {
              options: [
                {
                  label: 'Yes',
                  value: true,
                  icon: {
                    Asset: SvgCheckboxMarkedCircle,
                    color: 'success',
                    ml: '5px',
                  },
                },
                {
                  label: 'No',
                  value: false,
                  icon: {
                    Asset: SvgMinusCircle,
                    width: 26,
                    height: 26,
                    ml: '3px',
                  },
                },
              ],
              styles: {
                menu: (provided: any) => ({
                  ...provided,
                  width: 120,
                }),
              },
            },
          },
        ],
      },
    ],
    [data]
  );
  const subRow = (rowData: any) => {
    return <Box p="4">{rowData.subRow}</Box>;
  };
  const batchDelete = (selectedData: any) => {
    const selectedDids = selectedData.map((entry: any) => entry.did);
    setData(data.filter((entry: any) => !selectedDids.includes(entry.did)));
  };
  const batchActions: TableBatchActionType[] = [
    {
      icon: SvgDelete,
      label: 'Delete {0} item{s}',
      buttonProps: { variant: 'ghost' },
      needsSelection: true,
      click: batchDelete,
    },
    {
      label: 'Custom Action',
      condition: data.length < 13,
      click: () => {
        alert('Clicked!');
      },
    },
  ];
  const pageSizes = [5, 10, 20, 30];
  const title = (
    <Text variant="sh1" color="gray.1">
      Table Demo
    </Text>
  );

  const rowActions: TableRowActionType[] = [
    {
      id: 'add',
      Content: ButtonSmall,
      ContentProps: { variant: 'primary' },
      action: (rowData, rowIndex) => {
        alert('Row Action ' + rowIndex);
      },
      ContentChildren: 'Add',
      onlyShowOnHover: true,
      disabledTooltip: (rowData) => {
        console.log('-- rowData =', rowData);
        return 'This button is disabled.';
      },
      disabled: () => true,
    },
    {
      id: 'delete',
      Content: IconButton,
      ContentProps: {
        Asset: SvgDeleteOutline,
        width: 24,
        height: 24,
        color: 'gray.3',
      },
      action: (rowData) => {
        setData(data.filter((entry: any) => entry.did !== rowData.did));
      },
      onlyShowOnHover: true,
    },
  ];

  return (
    <Table
      title={title}
      columns={columns}
      data={data}
      updateData={setData}
      batchActions={batchActions}
      rowActions={rowActions}
      subRow={subRow}
      sortable
      selectable
      pageSize={5}
      pageSizes={pageSizes}
      canSkipPage
      empty={{
        icon: (
          <IconCircled
            Asset={SvgCoins}
            bg="gray.4"
            color="gray.3"
            width={48}
            height={48}
            scale={0.8}
          />
        ),
        copy: (
          <Text fontSize="2" color="gray.2" mt="m">
            No Item Exist
          </Text>
        ),
      }}
    />
  );
};

const tableExpandableInitialDataGenerator = (count: number) =>
  Array.from({ length: count }).map((e, i) => ({
    did: [1, 2].includes(i) ? '' : `0x0000000000${i}`,
    provider: `0x0000000000${i}`,
    buyLockup: '30 Sep, 2020',
    accredited: Math.random() >= 0.5,
    subRow: `Lorem ipsum dolor sitamet... ${i}`,
  }));

const tableExpandableInitialData = tableExpandableInitialDataGenerator(10);

export const TableExpandable = () => {
  const [pageStart] = useState(0);
  const pageSize = 5;
  const [data, setData] = useState({
    data: [],
    count: 0,
    next: null,
  });

  const fetchData = ({ start }: { start: number }) => {
    start = Math.min(start, tableExpandableInitialData.length - pageSize - 1);
    const newData = {
      data: tableExpandableInitialData.slice(start, start + pageSize),
      count: 10,
      next: start >= tableExpandableInitialData.length - 1 ? null : true,
    };

    setData(newData);
  };

  useEffect(() => {
    fetchData({ start: 0 });
  }, []);

  const getCustomHeaderProperties = () => ({
    borderBottom: `2px solid ${themeDefinitions.colors.gray[4]}`,
  });
  const getCustomRowProperties = (index: number) =>
    [0, 1].includes(index)
      ? {
          borderBottom: 'none',
        }
      : {
          borderBottom: `2px solid ${themeDefinitions.colors.gray[4]}`,
        };

  const getDefaultCellProperties = () => ({
    borderBottom: `2px solid ${themeDefinitions.colors.gray[4]}`,
  });

  const columns = useMemo(
    () => [
      {
        Header: 'Claims',
        columns: [
          {
            Header: 'Target Identity',
            accessor: 'did',
            getCustomCellProperties: () => ({
              borderBottom: 'none',
              borderRight: `2px solid ${themeDefinitions.colors.gray[4]}`,
            }),
            getCustomHeaderProperties: () => ({
              borderRight: `2px solid ${themeDefinitions.colors.gray[4]}`,
            }),
          },
          {
            Header: 'Provider',
            accessor: 'provider',
          },
          {
            Header: 'Buy Lockup',
            accessor: 'buyLockup',
          },
          {
            Header: 'Accredited',
            accessor: 'accredited',
            formatter: (state: any) =>
              state ? (
                <Icon
                  Asset={SvgCheckboxMarkedCircle}
                  width={22}
                  height={22}
                  color="success"
                />
              ) : (
                <Icon
                  Asset={SvgMinusCircle}
                  width={26}
                  height={26}
                  ml="-2px"
                  color="gray.3"
                />
              ),
          },
        ],
      },
    ],
    []
  );

  const batchActions: TableBatchActionType[] = [
    {
      icon: SvgDelete,
      label: 'Delete {0} item{s}',
      buttonProps: { variant: 'ghost' },
      needsSelection: true,
      click: () => {},
    },
  ];
  const pageSizes = [5, 10, 20, 30];
  const title = (
    <Text variant="sh1" color="gray.1">
      Table Expandable Demo
    </Text>
  );

  const rowActions: TableRowActionType[] = [
    {
      id: 'delete',
      Content: IconButton,
      ContentProps: {
        Asset: SvgDeleteOutline,
        width: 24,
        height: 24,
        color: 'gray.3',
      },
      action: () => {},
      onlyShowOnHover: true,
    },
  ];

  return (
    <Table
      title={title}
      columns={columns}
      data={data}
      fetchData={fetchData}
      pageStart={pageStart}
      updateData={setData}
      batchActions={batchActions}
      rowActions={rowActions}
      sortable
      selectable
      pageSize={pageSize}
      pageSizes={pageSizes}
      empty={{
        icon: (
          <IconCircled
            Asset={SvgCoins}
            bg="gray.4"
            color="gray.3"
            width={48}
            height={48}
            scale={0.8}
          />
        ),
        copy: (
          <Text fontSize="2" color="gray.2" mt="m">
            No Item Exist
          </Text>
        ),
      }}
      getCustomHeaderDefaultColumnProperties={getCustomHeaderProperties}
      getDefaultCellProperties={getDefaultCellProperties}
      getCustomRowProperties={getCustomRowProperties}
      rowsIndexesCheckboxesDisabled={[0, 3, 5]}
      rowsIndexesCheckboxesHidden={[1, 2]}
      paginationLabel="Identities per page"
      selectionRowCellStyle={{
        borderBottom: 'none',
      }}
      setPageSize={() => {}}
    />
  );
};
