import { useState } from 'react';

import { ZoomInOutlined } from '@ant-design/icons';
import { Button, Modal, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';

import { Text } from 'components';
import { AuditLogActionEnum } from 'enums';
import { AuditLog } from 'types';
import { renderLongColumnValue } from 'helpers';

import './action-cell.css';

export const ActionCell = ({ record }: { record: AuditLog }) => {
  const [opened, setOpened] = useState(false);

  const columns: ColumnsType<{
    field: string;
    from: any;
    to: any;
  }> = [
    {
      title: 'Field',
      dataIndex: 'field',
      key: 'field',
      render: (value) => <Text strong>{value}</Text>,
      width: '20%',
    },
  ];

  if (record.action === AuditLogActionEnum.update) {
    columns.push({
      title: 'Old value',
      dataIndex: 'from',
      key: 'from',
      width: '40%',
      ellipsis: false,
      render: (value) => {
        if (value === null || value === undefined) {
          return <Text type="secondary">-</Text>;
        }
        if (typeof value === 'object') {
          return renderLongColumnValue(JSON.stringify(value, null, 2));
        }
        return renderLongColumnValue(String(value));
      },
    });
  }

  columns.push({
    title: 'New value',
    dataIndex: 'to',
    key: 'to',
    width: '40%',
    ellipsis: false,
    render: (value) => {
      if (value === null || value === undefined) {
        return <Text type="secondary">-</Text>;
      }
      if (typeof value === 'object') {
        return renderLongColumnValue(JSON.stringify(value, null, 2));
      }
      return renderLongColumnValue(String(value));
    },
  });

  if (!record.data) {
    return null;
  }

  const newData = JSON.parse(record.data || '{}');
  const previousData = JSON.parse(record.previousData || '{}');
  const changes = Object.entries(newData).map(([key, value]) => ({
    field: key,
    from: previousData[key],
    to: value,
  }));

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        gap: '16px',
      }}
    >
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <Button
          size="small"
          icon={<ZoomInOutlined />}
          onClick={() => setOpened((prev) => !prev)}
        >
          Details
        </Button>
      </div>
      {opened && (
        <Modal
          open={opened}
          onOk={() => setOpened(false)}
          onCancel={() => setOpened(false)}
          style={{ minWidth: '60vw' }}
          styles={{
            body: {
              maxHeight: '500px',
              overflow: 'auto',
            },
          }}
        >
          <Table
            dataSource={changes}
            pagination={false}
            rowKey="field"
            bordered
            size="small"
            columns={columns}
            style={{ marginTop: '48px' }}
            rowClassName={(row) => {
              return record.action === AuditLogActionEnum.update &&
                row.from !== row.to
                ? 'highlight-changed-row'
                : '';
            }}
          />
        </Modal>
      )}
    </div>
  );
};
