import { useState } from 'react';
import {
  Typography,
  Form,
  Input,
  InputNumber,
  Switch,
  Button,
  Card,
  Space,
  Alert,
  Result,
  message,
} from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';

interface RegisterData {
  name: string;
  slug: string;
  domain: string;
  basePath: string;
  composeProject: string;
  portConfig: { api: number; admin: number; postgres: number; nginx: number };
  adminEmail: string;
  enableMedia: boolean;
  enableChat: boolean;
  enableGancio: boolean;
  enableListmonk: boolean;
  enableMonitoring: boolean;
  enableDevTools: boolean;
  enablePayments: boolean;
  enableMeet: boolean;
  enableSms: boolean;
  enableSocial: boolean;
  enablePeople: boolean;
  notes: string;
}

const defaultData: RegisterData = {
  name: '',
  slug: '',
  domain: '',
  basePath: '/home/bunker-admin/changemaker.lite',
  composeProject: 'changemakerlite',
  portConfig: { api: 4002, admin: 3002, postgres: 5433, nginx: 80 },
  adminEmail: '',
  enableMedia: false,
  enableChat: false,
  enableGancio: false,
  enableListmonk: false,
  enableMonitoring: false,
  enableDevTools: false,
  enablePayments: false,
  enableMeet: false,
  enableSms: false,
  enableSocial: false,
  enablePeople: false,
  notes: '',
};

export default function RegisterInstancePage() {
  const navigate = useNavigate();
  const [data, setData] = useState<RegisterData>(defaultData);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [createdId, setCreatedId] = useState<string | null>(null);

  const update = (fields: Partial<RegisterData>) =>
    setData((prev) => ({ ...prev, ...fields }));

  const updatePort = (key: keyof RegisterData['portConfig'], value: number | null) =>
    setData((prev) => ({
      ...prev,
      portConfig: { ...prev.portConfig, [key]: value || 0 },
    }));

  const autoSlug = (name: string) =>
    name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');

  const handleSubmit = async () => {
    setSubmitting(true);
    setError(null);
    try {
      const payload = {
        ...data,
        adminEmail: data.adminEmail || 'admin@localhost',
      };
      const { data: result } = await api.post('/instances/register', payload);
      setCreatedId(result.data.id);
      message.success('Instance registered successfully');
    } catch (err: unknown) {
      const resp = (err as { response?: { data?: { error?: { message?: string } } } })?.response
        ?.data?.error;
      setError(resp?.message || 'Failed to register instance');
    } finally {
      setSubmitting(false);
    }
  };

  const canSubmit = data.name && data.slug && data.domain && data.basePath && data.composeProject;

  if (createdId) {
    return (
      <Result
        status="success"
        title="Instance Registered"
        subTitle={`${data.name} (${data.domain}) has been registered for monitoring.`}
        extra={[
          <Button key="view" type="primary" onClick={() => navigate(`/app/instances/${createdId}`)}>
            View Instance
          </Button>,
          <Button key="list" onClick={() => navigate('/app/instances')}>
            Back to List
          </Button>,
        ]}
      />
    );
  }

  return (
    <div style={{ maxWidth: 700, margin: '0 auto' }}>
      <Space style={{ marginBottom: 24 }}>
        <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/app/instances')} />
        <Typography.Title level={3} style={{ margin: 0 }}>
          Register Existing Instance
        </Typography.Title>
      </Space>

      <Alert
        message="Register an external CML instance"
        description="Add an existing Changemaker Lite deployment that was set up outside the control panel. CCP will monitor it (health checks, services, logs) but will not manage its secrets, provisioning, or backups."
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />

      {error && (
        <Alert
          message={error}
          type="error"
          showIcon
          closable
          onClose={() => setError(null)}
          style={{ marginBottom: 16 }}
        />
      )}

      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        <Card title="Instance Info" size="small">
          <Form layout="vertical">
            <Form.Item label="Name" required>
              <Input
                value={data.name}
                onChange={(e) => update({ name: e.target.value, slug: autoSlug(e.target.value) })}
                placeholder="Better Edmonton"
              />
            </Form.Item>
            <Form.Item label="Slug" required help="URL-safe identifier (auto-generated from name)">
              <Input
                value={data.slug}
                onChange={(e) => update({ slug: e.target.value })}
                placeholder="betteredmonton"
              />
            </Form.Item>
            <Form.Item label="Domain" required>
              <Input
                value={data.domain}
                onChange={(e) => update({ domain: e.target.value })}
                placeholder="betteredmonton.org"
              />
            </Form.Item>
            <Form.Item label="Admin Email">
              <Input
                value={data.adminEmail}
                onChange={(e) => update({ adminEmail: e.target.value })}
                placeholder="admin@betteredmonton.org"
                type="email"
              />
            </Form.Item>
          </Form>
        </Card>

        <Card title="Docker Configuration" size="small">
          <Form layout="vertical">
            <Form.Item
              label="Base Path"
              required
              help="Absolute path to the directory containing docker-compose.yml"
            >
              <Input
                value={data.basePath}
                onChange={(e) => update({ basePath: e.target.value })}
                placeholder="/home/bunker-admin/changemaker.lite"
              />
            </Form.Item>
            <Form.Item
              label="Compose Project"
              required
              help="Docker Compose project name (from COMPOSE_PROJECT_NAME or directory name)"
            >
              <Input
                value={data.composeProject}
                onChange={(e) => update({ composeProject: e.target.value })}
                placeholder="changemakerlite"
              />
            </Form.Item>
          </Form>
        </Card>

        <Card title="Port Mapping" size="small">
          <Form layout="vertical">
            <Space wrap size="large">
              <Form.Item label="API Port">
                <InputNumber
                  value={data.portConfig.api}
                  onChange={(v) => updatePort('api', v)}
                  min={1}
                  max={65535}
                  style={{ width: 120 }}
                />
              </Form.Item>
              <Form.Item label="Admin Port">
                <InputNumber
                  value={data.portConfig.admin}
                  onChange={(v) => updatePort('admin', v)}
                  min={1}
                  max={65535}
                  style={{ width: 120 }}
                />
              </Form.Item>
              <Form.Item label="PostgreSQL Port">
                <InputNumber
                  value={data.portConfig.postgres}
                  onChange={(v) => updatePort('postgres', v)}
                  min={1}
                  max={65535}
                  style={{ width: 120 }}
                />
              </Form.Item>
              <Form.Item label="Nginx Port">
                <InputNumber
                  value={data.portConfig.nginx}
                  onChange={(v) => updatePort('nginx', v)}
                  min={1}
                  max={65535}
                  style={{ width: 120 }}
                />
              </Form.Item>
            </Space>
          </Form>
        </Card>

        <Card title="Features (informational)" size="small">
          <Space direction="vertical" style={{ width: '100%' }}>
            <Space>
              <Switch checked={data.enableMedia} onChange={(v) => update({ enableMedia: v })} />
              <span>Media Manager</span>
            </Space>
            <Space>
              <Switch checked={data.enableListmonk} onChange={(v) => update({ enableListmonk: v })} />
              <span>Newsletter (Listmonk)</span>
            </Space>
            <Space>
              <Switch checked={data.enableGancio} onChange={(v) => update({ enableGancio: v })} />
              <span>Events (Gancio)</span>
            </Space>
            <Space>
              <Switch checked={data.enableChat} onChange={(v) => update({ enableChat: v })} />
              <span>Chat</span>
            </Space>
            <Space>
              <Switch checked={data.enableMonitoring} onChange={(v) => update({ enableMonitoring: v })} />
              <span>Monitoring</span>
            </Space>
            <Space>
              <Switch checked={data.enableDevTools} onChange={(v) => update({ enableDevTools: v })} />
              <span>Dev Tools (Code Server, Gitea, n8n, Homepage, Excalidraw)</span>
            </Space>
            <Space>
              <Switch checked={data.enablePayments} onChange={(v) => update({ enablePayments: v })} />
              <span>Payments (Vaultwarden)</span>
            </Space>
            <Space>
              <Switch checked={data.enableMeet} onChange={(v) => update({ enableMeet: v })} />
              <span>Video Conferencing (Jitsi Meet)</span>
            </Space>
            <Space>
              <Switch checked={data.enableSms} onChange={(v) => update({ enableSms: v })} />
              <span>SMS Campaigns</span>
            </Space>
            <Space>
              <Switch checked={data.enableSocial} onChange={(v) => update({ enableSocial: v })} />
              <span>Social Connections</span>
            </Space>
            <Space>
              <Switch checked={data.enablePeople} onChange={(v) => update({ enablePeople: v })} />
              <span>People CRM</span>
            </Space>
          </Space>
        </Card>

        <Card title="Notes" size="small">
          <Input.TextArea
            value={data.notes}
            onChange={(e) => update({ notes: e.target.value })}
            rows={3}
            placeholder="Optional notes about this instance..."
          />
        </Card>

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
          <Button onClick={() => navigate('/app/instances')}>Cancel</Button>
          <Button type="primary" loading={submitting} disabled={!canSubmit} onClick={handleSubmit}>
            Verify & Register
          </Button>
        </div>
      </Space>
    </div>
  );
}
