import React, { useState, useMemo } from "react";
import { Story, Meta } from "@storybook/react/types-6-0";

import { ThemeProvider } from "../ThemeProvider";
import Table, { TableProps } from "./Table";
import { StyledLink as Link } from "baseui/link";
import { TableBuilderColumn } from "baseui/table-semantic";

export default {
  title: "Components/Content/Table",
  component: Table,
} as Meta;

const Template: Story<TableProps> = (args) => {
  const [sortColumn, setSortColumn] = useState("bar");
  const [sortAsc, setSortAsc] = useState(true);
  const [data] = useState([
    {
      foo: 10,
      bar: "Offices",
      url: "https://example.com/b",
    },
    {
      foo: 1,
      bar: "Factories",
      url: "https://example.com/c",
    },
    {
      foo: 2,
      bar: "Storage",
      url: "https://example.com/a",
    },
  ]);
  const sortedData = useMemo(() => {
    return data.slice().sort((a: any, b: any) => {
      const left = sortAsc ? a : b;
      const right = sortAsc ? b : a;
      const leftValue = String(left[sortColumn]);
      const rightValue = String(right[sortColumn]);
      return leftValue.localeCompare(rightValue, "en", {
        numeric: true,
        sensitivity: "base",
      });
    });
  }, [sortColumn, sortAsc, data]);
  function handleSort(id: string) {
    if (id === sortColumn) {
      setSortAsc((asc) => !asc);
    } else {
      setSortColumn(id);
      setSortAsc(true);
    }
  }
  return (
    <ThemeProvider>
      <Table
        data={sortedData}
        sortColumn={sortColumn}
        sortOrder={sortAsc ? "ASC" : "DESC"}
        onSort={handleSort}
      >
        <TableBuilderColumn id="bar" header="Building type" sortable>
          {(row) => <Link href={row.url}>{row.bar}</Link>}
        </TableBuilderColumn>
        <TableBuilderColumn id="foo" header="Quantity" numeric sortable>
          {(row) => row.foo}
        </TableBuilderColumn>
      </Table>
    </ThemeProvider>
  );
};

export const Default = Template.bind({});
Default.args = {};
