import type { TableColumnsType } from 'antd';
import { Button, Table } from 'antd';
import { ReportDetail } from 'models';
import { useReportList } from 'queries/report';
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { downloadReport } from 'request/report';

const ReportTable: React.FC = () => {
  const { isLoading, data: reportData } = useReportList({
    page_size: 100,
  });
  const report_data: any = reportData;
  const navigate = useNavigate();

  const [pagination, setPagination] = useState(() => ({
    page: report_data?.page.total_pages || 1,
    page_size: 10,
  }));

  const handleDownloadReport = async (report_id: string) => {
    const {file, filename} = await downloadReport(report_id);
    const anchorElement = document.createElement('a');
    anchorElement.href = URL.createObjectURL(file);
    anchorElement.download = filename;

    document.body.appendChild(anchorElement);
    anchorElement.click();

    // Clean up
    document.body.removeChild(anchorElement);
    URL.revokeObjectURL(anchorElement.href);
  };

  const columns: TableColumnsType<ReportDetail> = [
    {
      title: 'ID',
      dataIndex: 'ID',
      key: 'ID',
    },
    {
      title: 'Created Date',
      dataIndex: 'Created Date',
      key: 'Created Date',
      render: (_, record) => {
        return <span>{record['Created Date'].toString().split('T')[0]}</span>;
      },
    },
    {
      title: 'No. Requests',
      dataIndex: 'No. Requests',
      key: 'No. Requests',
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (_, record) => {
        return <>{record.Status}</>;
      },
    },
    {
      title: 'Purchase Date Acc',
      dataIndex: 'Purchase Date Acc',
      key: 'Purchase Date Acc',
      render: (_, record) => {
        const isAbnormal = record['Purchase Date Acc'] * 100 < 98;
        return (
          <span style={{ color: isAbnormal ? 'red' : '' }}>
            {record['Purchase Date Acc'] &&
              (Number(record['Purchase Date Acc']) * 100)?.toFixed(2)}
          </span>
        );
      },
    },

    {
      title: 'Retailer Acc',
      dataIndex: 'Retailer Acc',
      key: 'Retailer Acc',
      render: (_, record) => {
        const isAbnormal = record['Retailer Acc'] * 100 < 98;
        return (
          <span style={{ color: isAbnormal ? 'red' : '' }}>
            {record['Retailer Acc'] &&
              (Number(record['Retailer Acc']) * 100)?.toFixed(2)}
          </span>
        );
      },
    },
    {
      title: 'IMEI Acc',
      dataIndex: 'IMEI Acc',
      key: 'IMEI Acc',
      render: (_, record) => {
        const isAbnormal = record['IMEI Acc'] * 100 < 98;
        return (
          <span style={{ color: isAbnormal ? 'red' : '' }}>
            {record['IMEI Acc'] &&
              (Number(record['IMEI Acc']) * 100)?.toFixed(2)}
          </span>
        );
      },
    },
    {
      title: 'Avg Accuracy',
      dataIndex: 'Avg Accuracy',
      key: 'Avg Accuracy',
      render: (_, record) => {
        const isAbnormal = record['Avg Accuracy'] * 100 < 98;
        return (
          <span style={{ color: isAbnormal ? 'red' : '' }}>
            {record['Avg Accuracy'] &&
              (Number(record['Avg Accuracy']) * 100)?.toFixed(2)}
          </span>
        );
      },
    },
    {
      title: 'Avg Client Request Time',
      dataIndex: 'Avg. Client Request Time',
      key: 'Avg. Client Request Time',
      render: (_, record) => {
        const isAbnormal = record['Avg Client Request Time'] > 2;
        return (
          <span style={{ color: isAbnormal ? 'red' : '' }}>
            {record['Avg Client Request Time'] &&
              Number(record['Avg Client Request Time'])?.toFixed(2)}
          </span>
        );
      },
    },
    {
      title: 'Avg. OCR Processing Time',
      dataIndex: 'Avg. OCR Processing Time',
      key: 'Avg. OCR Processing Time',
      render: (_, record) => {
        const isAbnormal = record['Avg. OCR Processing Time'] > 2;
        return (
          <span style={{ color: isAbnormal ? 'red' : '' }}>
            {record['Avg. OCR Processing Time'] &&
              Number(record['Avg. OCR Processing Time'])?.toFixed(2)}
          </span>
        );
      },
    },
    {
      title: 'Actions',
      dataIndex: 'actions',
      key: 'actions',
      width: 200,
      render: (_, record) => {
        return (
          <div style={{ flexDirection: 'row' }}>
            <Button
              onClick={() => {
                navigate(`/reports/${record.report_id}/detail`);
              }}
              style={{ marginRight: 10 }}
            >
              Detail
            </Button>
            <Button onClick={() => handleDownloadReport(record.report_id)}>
              Download
            </Button>
          </div>
        );
      },
    },
  ];

  return (
    <>
      <Table
        loading={isLoading}
        columns={columns}
        dataSource={(report_data && report_data?.report_detail) || []}
        bordered
        size='small'
        pagination={{
          current: pagination.page,
          pageSize: pagination.page_size,
          total: report_data?.count || 0,
          onChange: (page, pageSize) => {
            setPagination({ page, page_size: pageSize || 10 });
          },
          showSizeChanger: false,
        }}
      />
    </>
  );
};

export default ReportTable;
