import { useMutation } from '@redwoodjs/web'
import { toast } from '@redwoodjs/web/toast'
import { Link, routes } from '@redwoodjs/router'

import { QUERY } from 'src/components/Account/AccountsCell'

import { useTable, usePagination, useSortBy, useFlexLayout } from 'react-table'
// import { IndeterminateCheckbox } from 'src/components/fn/IndeterminateCheckbox'

const DELETE_ACCOUNT_MUTATION = gql`
  mutation DeleteAccountMutation($id: Int!) {
    deleteAccount(id: $id) {
      id
    }
  }
`

const MAX_STRING_LENGTH = 255

const truncate = (text) => {
  let output = text
  if (text && text.length > MAX_STRING_LENGTH) {
    output = output.substring(0, MAX_STRING_LENGTH) + '...'
  }
  return output
}

const jsonTruncate = (obj) => {
  return truncate(JSON.stringify(obj, null, 2))
}

const timeTag = (datetime) => {
  return (
    <time dateTime={datetime} title={datetime}>
      {new Date(datetime).toLocaleDateString()}
    </time>
  )
}

const checkboxInputTag = (checked) => {
  return <input type="checkbox" checked={checked} disabled />
}

const Table = ({ columns, data }) => {
  const {
    page,
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    canPreviousPage,
    canNextPage,
    pageOptions,
    pageCount,
    gotoPage,
    nextPage,
    previousPage,
    setPageSize,
    allColumns,
    state: { pageIndex, pageSize },
  } = useTable(
    {
      columns,
      data,
      initialState: { pageIndex: 0 },

      // grr, hiding columns is completely fucking useless
      // hiddenColumns: () => {
      //   const hiddenColumnIds = []
      //   columns.foreach((col) => {
      //     if (col.isVisible === false) {
      //       hiddenColumnIds.push(col.id)
      //     }
      //   })

      //   return hiddenColumnIds
      // },
    },
    useFlexLayout,
    // useFilters,
    // useGlobalFilter,
    useSortBy,
    usePagination
  )

  return (
    <>
      <table
        className="uk-table uk-table-small uk-table-striped uk-table-hover"
        {...getTableProps()}
      >
        <thead>
          {headerGroups.map((headerGroup, hri) => (
            <tr {...headerGroup.getHeaderGroupProps()} key={hri}>
              {headerGroup.headers.map((column, i) => {
                return (
                  <>
                    {columns[i].isVisible === false ? (
                      false
                    ) : (
                      <th
                        key={column.id}
                        {...column.getHeaderProps([
                          column.getSortByToggleProps(),
                          {
                            className: column.classNameHead,
                          },
                        ])}
                      >
                        {column.render('Header')}
                        <span>
                          {column.isSorted
                            ? column.isSortedDesc
                              ? ' 🔽'
                              : ' 🔼'
                            : ''}
                        </span>
                      </th>
                    )}
                  </>
                )
              })}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {page.map((row, tri) => {
            prepareRow(row)
            return (
              <tr {...row.getRowProps()} key={tri}>
                {row.cells.map((cell, i) => {
                  return (
                    <>
                      {columns[i].isVisible === false ? (
                        false
                      ) : (
                        <td
                          key={cell.id}
                          {...cell.getCellProps([
                            {
                              className: cell.column.classNameCell,
                            },
                          ])}
                        >
                          {cell.render('Cell')}
                        </td>
                      )}
                    </>
                  )
                })}
              </tr>
            )
          })}
        </tbody>
      </table>

      <ul className="uk-subnav">
        {/* <li>
          <IndeterminateCheckbox {...getToggleHideAllColumnsProps()} />
          Toggle All
        </li> */}
        {allColumns.map((column, i) => (
          <li key={column.id}>
            {columns[i].isVisible === false ||
            columns[i].canToggle === false ? (
              false
            ) : (
              <label>
                <input type="checkbox" {...column.getToggleHiddenProps()} />
                {column.Header}
              </label>
            )}
          </li>
        ))}
      </ul>

      <div className="has-pagination" uk-flex-center="true">
        <button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
          {'<<'}
        </button>{' '}
        <button onClick={() => previousPage()} disabled={!canPreviousPage}>
          {'<'}
        </button>{' '}
        <button onClick={() => nextPage()} disabled={!canNextPage}>
          {'>'}
        </button>{' '}
        <button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
          {'>>'}
        </button>{' '}
        <span>
          Page{' '}
          <strong>
            {pageIndex + 1} of {pageOptions.length}
          </strong>{' '}
        </span>
        <span>
          | Go to page:{' '}
          <input
            type="number"
            defaultValue={pageIndex + 1}
            onChange={(e) => {
              const page = e.target.value ? Number(e.target.value) - 1 : 0
              gotoPage(page)
            }}
            style={{ width: '100px' }}
          />
        </span>{' '}
        <select
          value={pageSize}
          onChange={(e) => {
            setPageSize(Number(e.target.value))
          }}
        >
          {[5, 25, 100].map((pageSize) => (
            <option key={pageSize} value={pageSize}>
              Show {pageSize}
            </option>
          ))}
        </select>
      </div>
    </>
  )
}

const AccountsList = ({ accounts }) => {
  const [deleteAccount] = useMutation(DELETE_ACCOUNT_MUTATION, {
    onCompleted: () => {
      toast.success('Account deleted')
    },
    // This refetches the query on the list page. Read more about other ways to
    // update the cache over here:
    // https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates
    refetchQueries: [{ query: QUERY }],
    awaitRefetchQueries: true,
  })

  const onDeleteClick = (id) => {
    if (confirm('Are you sure you want to delete account ' + id + '?')) {
      deleteAccount({ variables: { id } })
    }
  }

  const columns = [
    {
      Header: 'Id',
      accessor: 'id',
      canSort: false,
      width: 45,
      isVisible: false,
      // Cell: ({ value }) => false,
    },
    {
      Header: 'UUID',
      accessor: 'uuid',
      canSort: false,
      width: 300,
      isVisible: false,
    },
    {
      Header: 'Account Name',
      accessor: 'name',
      sortType: 'basic',
      canToggle: false,
    },
    {
      Header: 'Primary Email',
      accessor: 'primaryEmail',
      sortType: 'basic',
      canSort: false,
      width: 220,
    },
    {
      Header: 'Password Hints',
      accessor: 'passwordHints',
      classNameCell: 'hide-as-barcode',
      width: 180,
      canSort: false,
    },
    {
      Header: 'Symbols',
      accessor: 'passwordSymbols',
      classNameCell: 'hide-as-barcode',
      width: 90,
      canSort: false,
    },
    {
      Header: 'Login URL',
      accessor: 'loginUrl',
      width: 120,
      canSort: false,
      Cell: ({ value }) => (
        <a
          href={value}
          target="_blank"
          className="uk-button uk-button-primary uk-button-small"
          rel="noreferrer"
        >
          Login
        </a>
      ),
    },
    {
      Header: 'Updated at',
      accessor: 'updatedAt',
      sortType: 'datetime',
      Cell: ({ value }) => timeTag(value),
    },
    // {
    //   Header: 'Created at',
    //   accessor: 'createdAt',
    //   sortType: 'datetime',
    //   isVisible: false,
    //   Cell: ({ value }) => timeTag(value),
    // },
    {
      Header: ' ',
      accessor: false,
      canSort: false,
      canToggle: false,
      width: 220,
      // isVisible: false,
      Cell: ({ cell }) => (
        <nav className="uk-subnav">
          <Link
            to={routes.account({ id: cell.row.values.id })}
            title={'View ' + cell.row.values.name + ' Account Details'}
            className="uk-button uk-button-small uk-button-default"
          >
            Show
          </Link>
          <Link
            to={routes.editAccount({ id: cell.row.values.id })}
            title={'Edit ' + cell.row.values.name}
            className="uk-button uk-button-small uk-button-secondary"
          >
            Edit
          </Link>
          <button
            href="#"
            title={'Delete ' + cell.row.values.name}
            className="uk-button uk-button-small uk-button-danger"
            onClick={() => onDeleteClick(cell.row.values.id)}
          >
            Delete
          </button>
        </nav>
      ),
    },
  ]

  // const data = accounts

  return <Table columns={columns} data={accounts} />
}

export default AccountsList
