import { Table, Tag } from 'antd';
import { CheckCircleOutlined, ClockCircleOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import type { VideoAnalytics } from '@/types/media';

interface ViewersTableProps {
  viewers: VideoAnalytics['registeredViewers'];
  loading?: boolean;
}

export default function ViewersTable({ viewers, loading }: ViewersTableProps) {
  const formatWatchTime = (seconds: number) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;

    if (hours > 0) {
      return `${hours}h ${minutes}m ${secs}s`;
    } else if (minutes > 0) {
      return `${minutes}m ${secs}s`;
    }
    return `${secs}s`;
  };

  const columns = [
    {
      title: 'User',
      dataIndex: 'userName',
      key: 'userName',
      render: (name: string | null) => name || <i style={{ color: '#999' }}>No name</i>,
    },
    {
      title: 'Email',
      dataIndex: 'userEmail',
      key: 'userEmail',
      ellipsis: true,
    },
    {
      title: 'Watch Time',
      dataIndex: 'watchTime',
      key: 'watchTime',
      render: (seconds: number) => formatWatchTime(seconds),
      sorter: (a: any, b: any) => a.watchTime - b.watchTime,
    },
    {
      title: 'Completion',
      dataIndex: 'completed',
      key: 'completed',
      render: (completed: boolean) =>
        completed ? (
          <Tag icon={<CheckCircleOutlined />} color="success">
            Completed
          </Tag>
        ) : (
          <Tag icon={<ClockCircleOutlined />} color="default">
            Partial
          </Tag>
        ),
      filters: [
        { text: 'Completed', value: true },
        { text: 'Partial', value: false },
      ],
      onFilter: (value: any, record: any) => record.completed === value,
    },
    {
      title: 'Viewed At',
      dataIndex: 'viewedAt',
      key: 'viewedAt',
      render: (date: string) => dayjs(date).format('MMM D, YYYY HH:mm'),
      sorter: (a: any, b: any) => dayjs(a.viewedAt).unix() - dayjs(b.viewedAt).unix(),
      defaultSortOrder: 'descend' as const,
    },
  ];

  return (
    <Table
      dataSource={viewers}
      columns={columns}
      rowKey="userId"
      loading={loading}
      pagination={{
        pageSize: 10,
        showSizeChanger: true,
        showTotal: (total) => `${total} viewers`,
      }}
      size="small"
    />
  );
}
