import { DownloadOutlined } from '@ant-design/icons';
import { t, Trans } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { Button, Card, Table, Typography } from 'antd';
import React from 'react';
import { CSVLink } from 'react-csv';
import {
  useSelectedShapeId,
  useShapes,
} from '../../components/annotator/hooks';
import { useStoreInstance } from '../../components/annotator/store-context';
import { EditableCell } from '../../components/editable-cell';
import { useInitialCardHeight } from '../../hooks/useInitialCardHeight';
import { shapesToCsv } from '../../utils/shape-convert';

export function ExtractInformation() {
  const { i18n } = useLingui();
  const storeInstance = useStoreInstance();
  const shapes = useShapes();
  const selectedShapeId = useSelectedShapeId();
  const tableAsCsv = shapesToCsv(shapes);
  const cardRef = React.useRef<HTMLDivElement>();
  const initialCardHeight = useInitialCardHeight(cardRef);

  return (
    <Card
      ref={cardRef}
      title={t(i18n)`Extracted Information`}
      style={{ height: '100%' }}
      bordered
      extra={
        <div>
          {tableAsCsv.length > 1 && (
            <Button type="link">
              <CSVLink
                data={tableAsCsv}
                filename={`extracted_data_${new Date().toISOString()}.csv`}
              >
                <Trans>
                  Export CSV <DownloadOutlined />
                </Trans>
              </CSVLink>
            </Button>
          )}
        </div>
      }
    >
      <Table
        pagination={false}
        scroll={{
          y: initialCardHeight ? initialCardHeight - 50 : 680,
        }}
        onRow={(record) => {
          return {
            onClick() {
              storeInstance.setSelectedShape(record.key);
            },
          };
        }}
        rowSelection={{
          hideSelectAll: true,
          columnWidth: 0,
          selectedRowKeys: [selectedShapeId],
          renderCell() {
            return null;
          },
        }}
        columns={[
          {
            title: t(i18n)`Label`,
            width: 120,
            render(_, record) {
              return <Typography.Text>{record.data?.label}</Typography.Text>;
            },
          },
          {
            title: t(i18n)`Value`,
            render(_, record) {
              return (
                <EditableCell
                  editable={{
                    onChange(value) {
                      storeInstance.setShapes((prev) =>
                        prev.map((shape) => {
                          if (shape.id === record.id) {
                            if (!shape.data)
                              shape.data = {
                                label: '',
                                value: '',
                              };
                            shape.data.value = value;
                          }

                          return shape;
                        }),
                      );
                    },
                  }}
                >
                  {record.data?.value}
                </EditableCell>
              );
            },
          },
        ]}
        dataSource={shapes.map((shape) => ({
          key: shape.id,
          ...shape,
        }))}
      />
    </Card>
  );
}
