import { useState, useEffect, useCallback } from 'react';
import { Typography, Button, Table, Tag, Space, message, Card, Modal, Descriptions, Alert } from 'antd';
import { CheckOutlined, CloseOutlined, ReloadOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import type { AgentRegistration } from '@/types/api';

const { Title } = Typography;

export default function AgentRegistrationsPage() {
  const [registrations, setRegistrations] = useState<AgentRegistration[]>([]);
  const [loading, setLoading] = useState(true);
  const [detailModal, setDetailModal] = useState<AgentRegistration | null>(null);

  const fetchRegistrations = useCallback(async () => {
    try {
      setLoading(true);
      const { data } = await api.get('/agents/registrations');
      setRegistrations(data);
    } catch {
      message.error('Failed to load registrations');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchRegistrations(); }, [fetchRegistrations]);

  const handleApprove = async (id: string) => {
    try {
      await api.post(`/agents/registrations/${id}/approve`);
      message.success('Registration approved — agent will receive certificates on next poll');
      fetchRegistrations();
      setDetailModal(null);
    } catch (err: unknown) {
      const error = err as { response?: { data?: { message?: string } } };
      message.error(error?.response?.data?.message || 'Failed to approve');
    }
  };

  const handleReject = async (id: string) => {
    try {
      await api.post(`/agents/registrations/${id}/reject`);
      message.success('Registration rejected');
      fetchRegistrations();
      setDetailModal(null);
    } catch {
      message.error('Failed to reject');
    }
  };

  const statusColor: Record<string, string> = {
    PENDING: 'orange',
    APPROVED: 'green',
    REJECTED: 'red',
    EXPIRED: 'default',
  };

  const columns = [
    { title: 'Slug', dataIndex: 'slug', key: 'slug' },
    { title: 'Domain', dataIndex: 'domain', key: 'domain' },
    { title: 'Agent URL', dataIndex: 'agentUrl', key: 'agentUrl' },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => <Tag color={statusColor[status]}>{status}</Tag>,
    },
    {
      title: 'Submitted',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: unknown, record: AgentRegistration) => (
        <Space>
          <Button type="link" size="small" onClick={() => setDetailModal(record)}>Details</Button>
          {record.status === 'PENDING' && (
            <>
              <Button type="primary" size="small" icon={<CheckOutlined />} onClick={() => handleApprove(record.id)}>
                Approve
              </Button>
              <Button danger size="small" icon={<CloseOutlined />} onClick={() => handleReject(record.id)}>
                Reject
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ];

  const pendingCount = registrations.filter(r => r.status === 'PENDING').length;

  return (
    <div style={{ padding: 24 }}>
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Title level={3} style={{ margin: 0 }}>
            Agent Registrations
            {pendingCount > 0 && <Tag color="orange" style={{ marginLeft: 8 }}>{pendingCount} pending</Tag>}
          </Title>
          <Button icon={<ReloadOutlined />} onClick={fetchRegistrations}>Refresh</Button>
        </div>

        {pendingCount > 0 && (
          <Alert
            type="warning"
            message={`${pendingCount} registration${pendingCount > 1 ? 's' : ''} awaiting approval`}
            description="Review the agent details below and approve or reject the registration. Approved agents will receive mTLS certificates automatically."
            showIcon
          />
        )}

        <Card>
          <Table
            columns={columns}
            dataSource={registrations}
            rowKey="id"
            loading={loading}
            pagination={{ pageSize: 20 }}
          />
        </Card>
      </Space>

      <Modal
        title={`Registration: ${detailModal?.slug}`}
        open={!!detailModal}
        onCancel={() => setDetailModal(null)}
        footer={detailModal?.status === 'PENDING' ? [
          <Button key="reject" danger onClick={() => detailModal && handleReject(detailModal.id)}>Reject</Button>,
          <Button key="approve" type="primary" onClick={() => detailModal && handleApprove(detailModal.id)}>Approve</Button>,
        ] : null}
        width={600}
      >
        {detailModal && (
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="Slug">{detailModal.slug}</Descriptions.Item>
            <Descriptions.Item label="Name">{detailModal.name}</Descriptions.Item>
            <Descriptions.Item label="Domain">{detailModal.domain}</Descriptions.Item>
            <Descriptions.Item label="Agent URL">{detailModal.agentUrl}</Descriptions.Item>
            <Descriptions.Item label="Base Path">{detailModal.basePath}</Descriptions.Item>
            <Descriptions.Item label="Compose Project">{detailModal.composeProject}</Descriptions.Item>
            <Descriptions.Item label="Status">
              <Tag color={statusColor[detailModal.status]}>{detailModal.status}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="Submitted">{new Date(detailModal.createdAt).toLocaleString()}</Descriptions.Item>
            {detailModal.approvedAt && (
              <Descriptions.Item label="Approved">{new Date(detailModal.approvedAt).toLocaleString()}</Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>
    </div>
  );
}
