import { useState, useEffect, useCallback } from 'react';
import {
  Typography,
  Card,
  Form,
  Input,
  Button,
  Alert,
  Space,
  Descriptions,
  Tag,
  Spin,
  Popconfirm,
  message,
} from 'antd';
import {
  CloudServerOutlined,
  LinkOutlined,
  DisconnectOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';

const { Title, Paragraph } = Typography;

interface RegistrationStatus {
  registered: boolean;
  ccpUrl: string | null;
  agentUrl: string | null;
  agentRunning: boolean;
}

export default function ControlPanelPage() {
  const [status, setStatus] = useState<RegistrationStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [registering, setRegistering] = useState(false);
  const [unregistering, setUnregistering] = useState(false);
  const [form] = Form.useForm();

  const fetchStatus = useCallback(async () => {
    try {
      setLoading(true);
      const { data } = await api.get('/api/ccp-registration/status');
      setStatus(data);
    } catch {
      message.error('Failed to load registration status');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleRegister = async (values: { ccpUrl: string; inviteCode: string; agentUrl: string }) => {
    try {
      setRegistering(true);
      const { data } = await api.post('/api/ccp-registration/register', values);
      if (data.success) {
        message.success(data.message);
        fetchStatus();
      } else {
        message.error(data.message || 'Registration failed');
      }
    } catch (err: unknown) {
      const error = err as { response?: { data?: { error?: { message?: string } } } };
      message.error(error?.response?.data?.error?.message || 'Registration failed');
    } finally {
      setRegistering(false);
    }
  };

  const handleUnregister = async () => {
    try {
      setUnregistering(true);
      const { data } = await api.post('/api/ccp-registration/unregister');
      if (data.success) {
        message.success(data.message);
        form.resetFields();
        fetchStatus();
      }
    } catch {
      message.error('Failed to unregister');
    } finally {
      setUnregistering(false);
    }
  };

  if (loading) {
    return (
      <div style={{ padding: 24, textAlign: 'center' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div style={{ padding: 24, maxWidth: 800 }}>
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        <div>
          <Title level={3} style={{ margin: 0 }}>
            <CloudServerOutlined style={{ marginRight: 8 }} />
            Control Panel Registration
          </Title>
          <Paragraph type="secondary" style={{ marginTop: 8 }}>
            Register this instance with a Changemaker Control Panel (CCP) for remote management,
            health monitoring, backups, and upgrades.
          </Paragraph>
        </div>

        {status?.registered ? (
          // ─── Registered State ────────────────────────────────
          <Space direction="vertical" style={{ width: '100%' }} size="middle">
            <Alert
              type="success"
              message="Registered with Control Panel"
              description="This instance is connected to a CCP. The agent handles health checks, lifecycle operations, and configuration sync."
              showIcon
              icon={<CheckCircleOutlined />}
            />

            <Card title="Connection Details">
              <Descriptions column={1} bordered size="small">
                <Descriptions.Item label="Control Panel URL">
                  <a href={status.ccpUrl || '#'} target="_blank" rel="noopener noreferrer">
                    {status.ccpUrl}
                  </a>
                </Descriptions.Item>
                <Descriptions.Item label="Agent URL">
                  {status.agentUrl}
                </Descriptions.Item>
                <Descriptions.Item label="Agent Status">
                  {status.agentRunning ? (
                    <Tag icon={<CheckCircleOutlined />} color="success">Running</Tag>
                  ) : (
                    <Tag icon={<CloseCircleOutlined />} color="error">Not Running</Tag>
                  )}
                </Descriptions.Item>
              </Descriptions>

              {!status.agentRunning && (
                <Alert
                  type="warning"
                  message="Agent container is not running"
                  description="The CCP agent may still be waiting for approval, or it may have stopped. Check the container logs for details."
                  showIcon
                  style={{ marginTop: 16 }}
                />
              )}

              <div style={{ marginTop: 24, textAlign: 'right' }}>
                <Popconfirm
                  title="Unregister from Control Panel?"
                  description="This will stop the agent and remove the CCP connection. You can re-register later with a new invite code."
                  onConfirm={handleUnregister}
                  okText="Yes, Unregister"
                  okButtonProps={{ danger: true }}
                >
                  <Button
                    danger
                    icon={<DisconnectOutlined />}
                    loading={unregistering}
                  >
                    Unregister
                  </Button>
                </Popconfirm>
              </div>
            </Card>
          </Space>
        ) : (
          // ─── Unregistered State ──────────────────────────────
          <Space direction="vertical" style={{ width: '100%' }} size="middle">
            <Alert
              type="info"
              message="Not registered with a Control Panel"
              description="Enter the CCP URL and invite code provided by your CCP administrator to register this instance for remote management."
              showIcon
            />

            <Card title="Register with Control Panel">
              <Form
                form={form}
                layout="vertical"
                onFinish={handleRegister}
                style={{ maxWidth: 500 }}
              >
                <Form.Item
                  label="Control Panel URL"
                  name="ccpUrl"
                  rules={[
                    { required: true, message: 'CCP URL is required' },
                    { type: 'url', message: 'Must be a valid URL' },
                  ]}
                  extra="The URL of the Changemaker Control Panel (e.g., https://ccp.example.com)"
                >
                  <Input placeholder="https://ccp.example.com" prefix={<LinkOutlined />} />
                </Form.Item>

                <Form.Item
                  label="Invite Code"
                  name="inviteCode"
                  rules={[{ required: true, message: 'Invite code is required' }]}
                  extra="Single-use code generated by the CCP admin (e.g., ABCD-1234)"
                >
                  <Input
                    placeholder="XXXX-XXXX"
                    style={{ fontFamily: 'monospace', letterSpacing: 2 }}
                    maxLength={20}
                  />
                </Form.Item>

                <Form.Item
                  label="Agent URL"
                  name="agentUrl"
                  rules={[
                    { required: true, message: 'Agent URL is required' },
                    { type: 'url', message: 'Must be a valid URL' },
                  ]}
                  extra="How the CCP can reach this machine (must be externally accessible). Include port 7443."
                >
                  <Input placeholder="https://this-server:7443" prefix={<LinkOutlined />} />
                </Form.Item>

                <Form.Item style={{ marginTop: 24 }}>
                  <Button
                    type="primary"
                    htmlType="submit"
                    icon={registering ? <LoadingOutlined /> : <CloudServerOutlined />}
                    loading={registering}
                    size="large"
                  >
                    Register with Control Panel
                  </Button>
                </Form.Item>
              </Form>
            </Card>

            <Card title="How it works" size="small">
              <ol style={{ paddingLeft: 20, margin: 0 }}>
                <li>Your CCP admin generates an invite code and shares it with you</li>
                <li>Enter the CCP URL, invite code, and this server's agent URL above</li>
                <li>The CCP agent starts and sends a registration request to the CCP</li>
                <li>The CCP admin approves the registration</li>
                <li>mTLS certificates are issued automatically for secure communication</li>
                <li>The CCP can now manage this instance remotely</li>
              </ol>
            </Card>
          </Space>
        )}
      </Space>
    </div>
  );
}
