import { Table, Tag, Button, Space, Tooltip, Empty } from 'antd';
import { ReloadOutlined, FileTextOutlined } from '@ant-design/icons';

export interface ServiceInfo {
  name: string;
  service: string;
  status: string;
  state: string;
  health: string;
  ports: string;
  createdAt: string;
  exitCode: number;
}

interface ServiceHealthGridProps {
  services: ServiceInfo[];
  loading?: boolean;
  onRestart?: (service: string) => void;
  onViewLogs?: (service: string) => void;
}

const stateColors: Record<string, string> = {
  running: 'green',
  exited: 'red',
  restarting: 'orange',
  paused: 'gold',
  dead: 'red',
  created: 'blue',
};

const healthColors: Record<string, string> = {
  healthy: 'green',
  unhealthy: 'red',
  starting: 'processing',
};

export default function ServiceHealthGrid({
  services,
  loading,
  onRestart,
  onViewLogs,
}: ServiceHealthGridProps) {
  if (!loading && services.length === 0) {
    return <Empty description="No containers found" />;
  }

  const columns = [
    {
      title: 'Service',
      dataIndex: 'service',
      key: 'service',
      render: (name: string) => <strong>{name}</strong>,
    },
    {
      title: 'Container',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => (
        <span style={{ fontSize: 12, fontFamily: 'monospace' }}>{name}</span>
      ),
    },
    {
      title: 'State',
      dataIndex: 'state',
      key: 'state',
      render: (state: string) => (
        <Tag color={stateColors[state] || 'default'}>{state.toUpperCase()}</Tag>
      ),
    },
    {
      title: 'Health',
      dataIndex: 'health',
      key: 'health',
      render: (health: string) => {
        if (!health || health === 'none' || health === '') {
          return <Tag>N/A</Tag>;
        }
        return <Tag color={healthColors[health] || 'default'}>{health}</Tag>;
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <span style={{ fontSize: 12 }}>{status}</span>
      ),
    },
    {
      title: 'Ports',
      dataIndex: 'ports',
      key: 'ports',
      render: (ports: string) => {
        if (!ports) return <span style={{ fontSize: 11, fontFamily: 'monospace' }}>-</span>;
        // Extract host ports from mappings like "0.0.0.0:13000->3000/tcp, [::]:13000->3000/tcp"
        // and render as clickable localhost links
        const hostPorts = new Set<number>();
        for (const match of ports.matchAll(/0\.0\.0\.0:(\d+)->/g)) {
          hostPorts.add(parseInt(match[1], 10));
        }
        if (hostPorts.size === 0) {
          return <span style={{ fontSize: 11, fontFamily: 'monospace' }}>{ports}</span>;
        }
        return (
          <Space size={4} wrap>
            {[...hostPorts].sort((a, b) => a - b).map((port) => (
              <a
                key={port}
                href={`http://localhost:${port}`}
                target="_blank"
                rel="noopener noreferrer"
                style={{ fontSize: 11, fontFamily: 'monospace' }}
              >
                :{port}
              </a>
            ))}
          </Space>
        );
      },
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 100,
      render: (_: unknown, record: ServiceInfo) => (
        <Space size="small">
          {onRestart && (
            <Tooltip title="Restart">
              <Button
                type="text"
                size="small"
                icon={<ReloadOutlined />}
                onClick={() => onRestart(record.service)}
              />
            </Tooltip>
          )}
          {onViewLogs && (
            <Tooltip title="View Logs">
              <Button
                type="text"
                size="small"
                icon={<FileTextOutlined />}
                onClick={() => onViewLogs(record.service)}
              />
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

  return (
    <Table
      dataSource={services}
      columns={columns}
      rowKey="name"
      loading={loading}
      pagination={false}
      size="small"
    />
  );
}
