import { useState, useEffect, useCallback } from 'react';
import { Typography, Button, Table, Tag, Space, message, Popconfirm, Card, Alert } from 'antd';
import { PlusOutlined, DeleteOutlined, CopyOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import type { AgentInviteCode } from '@/types/api';

const { Title, Text } = Typography;

export default function InviteCodesPage() {
  const [codes, setCodes] = useState<AgentInviteCode[]>([]);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);

  const fetchCodes = useCallback(async () => {
    try {
      setLoading(true);
      const { data } = await api.get('/invite-codes');
      setCodes(data.data || []);
    } catch {
      message.error('Failed to load invite codes');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleCreate = async () => {
    try {
      setCreating(true);
      const { data } = await api.post('/invite-codes');
      message.success(`Invite code created: ${data.code}`);
      fetchCodes();
    } catch {
      message.error('Failed to create invite code');
    } finally {
      setCreating(false);
    }
  };

  const handleRevoke = async (id: string) => {
    try {
      await api.delete(`/invite-codes/${id}`);
      message.success('Invite code revoked');
      fetchCodes();
    } catch {
      message.error('Failed to revoke invite code');
    }
  };

  const copyCode = (code: string) => {
    navigator.clipboard.writeText(code);
    message.success('Code copied to clipboard');
  };

  const columns = [
    {
      title: 'Code',
      dataIndex: 'code',
      key: 'code',
      render: (code: string) => (
        <Space>
          <Text code style={{ fontSize: 16 }}>{code}</Text>
          <Button type="text" size="small" icon={<CopyOutlined />} onClick={() => copyCode(code)} />
        </Space>
      ),
    },
    {
      title: 'Status',
      key: 'status',
      render: (_: unknown, record: AgentInviteCode) => {
        if (record.usedAt) return <Tag color="green">Used</Tag>;
        if (new Date(record.expiresAt) < new Date()) return <Tag color="red">Expired</Tag>;
        return <Tag color="blue">Active</Tag>;
      },
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: 'Expires',
      dataIndex: 'expiresAt',
      key: 'expiresAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: 'Created By',
      dataIndex: 'createdBy',
      key: 'createdBy',
      render: (user: AgentInviteCode['createdBy']) => user?.name || user?.email || '-',
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: unknown, record: AgentInviteCode) => {
        if (record.usedAt) return null;
        return (
          <Popconfirm title="Revoke this invite code?" onConfirm={() => handleRevoke(record.id)}>
            <Button type="text" danger icon={<DeleteOutlined />} size="small">Revoke</Button>
          </Popconfirm>
        );
      },
    },
  ];

  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 Invite Codes</Title>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate} loading={creating}>
            Generate Code
          </Button>
        </div>

        <Alert
          type="info"
          message="Invite codes are used by remote CML instances during setup to register with this control panel."
          description="Each code is single-use and expires after 24 hours. Share the code with the remote operator who will enter it during config.sh setup."
          showIcon
        />

        <Card>
          <Table
            columns={columns}
            dataSource={codes}
            rowKey="id"
            loading={loading}
            pagination={{ pageSize: 20 }}
          />
        </Card>
      </Space>
    </div>
  );
}
