import { useState, useEffect, useCallback } from 'react';
import { useNavigate, useOutletContext } from 'react-router-dom';
import {
  Card, Button, Form, Input, Select, Space, Tag, Typography, Spin, Alert,
  Descriptions, Steps, App, Grid, Divider, Result,
} from 'antd';
import {
  PhoneOutlined, CheckCircleOutlined, CloseCircleOutlined, SettingOutlined,
  CopyOutlined, EyeOutlined, EyeInvisibleOutlined, ApiOutlined,
  WifiOutlined, LinkOutlined, ThunderboltOutlined, ReloadOutlined,
  AndroidOutlined, CloudServerOutlined, RocketOutlined, SendOutlined,
  MessageOutlined, WarningOutlined, KeyOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/components/AppLayout';
import type {
  SmsSetupStatus, SmsSetupConfig, TailscaleDevice, SmsTestConnectionResult,
} from '@/types/sms';

const { Text, Paragraph } = Typography;

/** A single terminal command line with copy button */
function CmdLine({ cmd, comment }: { cmd: string; comment?: string }) {
  return (
    <div style={{ marginBottom: 6 }}>
      {comment && <Text type="secondary" style={{ fontSize: 12 }}># {comment}</Text>}
      {comment && <br />}
      <Text
        code
        copyable={{ text: cmd, tooltips: ['Copy', 'Copied!'] }}
        style={{ fontSize: 13, wordBreak: 'break-all' }}
      >
        {cmd}
      </Text>
    </div>
  );
}

export default function SmsSetupPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const { message } = App.useApp();
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  // State
  const [loading, setLoading] = useState(true);
  const [status, setStatus] = useState<SmsSetupStatus | null>(null);
  const [config, setConfig] = useState<SmsSetupConfig | null>(null);
  const [wizardMode, setWizardMode] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);

  // Step 1: Key generation
  const [generatedKey, setGeneratedKey] = useState('');
  const [showGeneratedKey, setShowGeneratedKey] = useState(false);
  const [generatingKey, setGeneratingKey] = useState(false);

  // Step 2: Connection
  const [tailscaleApiKey, setTailscaleApiKey] = useState('');
  const [tailscaleTailnet, setTailscaleTailnet] = useState('');
  const [devices, setDevices] = useState<TailscaleDevice[]>([]);
  const [selectedDevice, setSelectedDevice] = useState<string | null>(null);
  const [discoveringDevices, setDiscoveringDevices] = useState(false);
  const [termuxUrl, setTermuxUrl] = useState('');
  const [termuxApiKey, setTermuxApiKey] = useState('');
  const [connectionMethod, setConnectionMethod] = useState<'tailscale' | 'manual'>('tailscale');

  // Step 3: Test & Save
  const [testResult, setTestResult] = useState<SmsTestConnectionResult | null>(null);
  const [testing, setTesting] = useState(false);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  // Send Test SMS
  const [testPhone, setTestPhone] = useState('');
  const [testSending, setTestSending] = useState(false);

  useEffect(() => {
    setPageHeader({ title: 'SMS Setup' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  const fetchStatus = useCallback(async () => {
    setLoading(true);
    try {
      const [statusRes, configRes] = await Promise.all([
        api.get<SmsSetupStatus>('/sms/setup/status'),
        api.get<SmsSetupConfig>('/sms/setup/config'),
      ]);
      setStatus(statusRes.data);
      setConfig(configRes.data);

      // Auto-enter wizard if not configured
      if (!statusRes.data.configured) {
        setWizardMode(true);
      }
    } catch {
      message.error('Failed to load SMS setup status');
    } finally {
      setLoading(false);
    }
  }, [message]);

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

  // --- Handlers ---

  const handleGenerateKey = async () => {
    setGeneratingKey(true);
    try {
      const res = await api.post<{ key: string }>('/sms/setup/generate-key');
      setGeneratedKey(res.data.key);
      setTermuxApiKey(res.data.key);
      setShowGeneratedKey(true);
      message.success('API key generated');
    } catch {
      message.error('Failed to generate key');
    } finally {
      setGeneratingKey(false);
    }
  };

  const handleDiscoverDevices = async () => {
    if (!tailscaleApiKey) {
      message.warning('Enter a Tailscale API key first');
      return;
    }
    setDiscoveringDevices(true);
    setDevices([]);
    setSelectedDevice(null);
    try {
      const res = await api.post<{ devices: TailscaleDevice[] }>('/sms/setup/tailscale/devices', {
        apiKey: tailscaleApiKey,
        tailnet: tailscaleTailnet || undefined,
      });
      setDevices(res.data.devices);

      // Auto-select if only one Android device
      const androidDevices = res.data.devices.filter(d => d.os.toLowerCase() === 'android');
      if (androidDevices.length === 1 && androidDevices[0]) {
        setSelectedDevice(androidDevices[0].id);
        // Auto-fill URL
        const ipv4 = androidDevices[0].addresses.find(a => !a.includes(':'));
        if (ipv4) {
          setTermuxUrl(`http://${ipv4}:5001`);
        }
      }

      message.success(`Found ${res.data.devices.length} device(s)`);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })?.response?.data?.error?.message || 'Failed to discover devices';
      message.error(msg);
    } finally {
      setDiscoveringDevices(false);
    }
  };

  const handleDeviceSelect = (deviceId: string) => {
    setSelectedDevice(deviceId);
    const device = devices.find(d => d.id === deviceId);
    if (device) {
      const ipv4 = device.addresses.find(a => !a.includes(':'));
      if (ipv4) {
        setTermuxUrl(`http://${ipv4}:5001`);
      }
    }
  };

  const handleTestConnection = async () => {
    if (!termuxUrl || !termuxApiKey) {
      message.warning('Enter both URL and API key');
      return;
    }
    setTesting(true);
    setTestResult(null);
    try {
      const res = await api.post<SmsTestConnectionResult>('/sms/setup/test-connection', {
        url: termuxUrl,
        apiKey: termuxApiKey,
      });
      setTestResult(res.data);
      if (res.data.success) {
        message.success('Connection successful — phone is reachable and key is valid!');
      } else {
        message.error(res.data.error || 'Connection failed');
      }
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })?.response?.data?.error?.message || 'Test failed';
      setTestResult({ success: false, error: msg });
      message.error(msg);
    } finally {
      setTesting(false);
    }
  };

  const handleSaveConfig = async () => {
    setSaving(true);
    try {
      const selectedDeviceObj = devices.find(d => d.id === selectedDevice);

      await api.post('/sms/setup/save-config', {
        enableSms: true,
        smsTermuxApiUrl: termuxUrl,
        smsTermuxApiKey: termuxApiKey,
        ...(tailscaleApiKey ? {
          smsTailscaleApiKey: tailscaleApiKey,
          smsTailscaleTailnet: tailscaleTailnet || '',
          smsTailscaleDeviceId: selectedDevice || '',
          smsTailscaleDeviceName: selectedDeviceObj?.hostname || selectedDeviceObj?.name || '',
        } : {}),
      });

      setSaved(true);
      message.success('SMS configuration saved!');

      // Refresh status
      setTimeout(() => {
        fetchStatus();
        setWizardMode(false);
      }, 1000);
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })?.response?.data?.error?.message || 'Failed to save';
      message.error(msg);
    } finally {
      setSaving(false);
    }
  };

  const handleSendTest = async () => {
    if (!testPhone.trim()) {
      message.warning('Enter a phone number to send a test SMS');
      return;
    }
    setTestSending(true);
    try {
      const res = await api.post<{ status: string; termuxResult?: { success: boolean; error?: string } }>('/sms/messages/send', {
        phone: testPhone.trim(),
        message: 'Test SMS from Changemaker',
      });
      if (res.data.termuxResult?.success === false) {
        const err = res.data.termuxResult.error || 'Unknown error';
        if (err.includes('401') || err.includes('Authentication')) {
          message.error('API key mismatch — the key saved here does not match the phone. Re-run setup or update the key on the phone.');
        } else {
          message.error(`SMS failed: ${err}`);
        }
      } else {
        message.success('Test SMS sent!');
      }
    } catch {
      message.error('Failed to send test SMS');
    } finally {
      setTestSending(false);
    }
  };

  // --- Render ---

  if (loading) {
    return <Spin size="large" style={{ display: 'block', margin: '100px auto' }} />;
  }

  return (
    <Space direction="vertical" size="large" style={{ width: '100%' }}>
      {/* Status Card — always visible */}
      <Card title={<><PhoneOutlined /> SMS Connection Status</>}>
        <Descriptions column={{ xs: 1, sm: 2 }} bordered size="small">
          <Descriptions.Item label="Connection">
            {status?.connected
              ? <Tag icon={<CheckCircleOutlined />} color="success">Connected</Tag>
              : status?.configured
                ? <Tag icon={<CloseCircleOutlined />} color="error">Disconnected</Tag>
                : <Tag color="default">Not Configured</Tag>}
          </Descriptions.Item>
          <Descriptions.Item label="Config Source">
            {status?.configured
              ? <Tag color={status.source === 'database' ? 'blue' : 'orange'}>{status.source === 'database' ? 'Database' : 'Environment'}</Tag>
              : <Tag color="default">None</Tag>}
          </Descriptions.Item>
          <Descriptions.Item label="Tailscale">
            {status?.tailscaleConfigured
              ? <Tag icon={<CheckCircleOutlined />} color="success">Configured</Tag>
              : <Tag color="default">Not Configured</Tag>}
          </Descriptions.Item>
          <Descriptions.Item label="Phone URL">
            {config?.smsTermuxApiUrl
              ? <Text copyable>{config.smsTermuxApiUrl}</Text>
              : <Text type="secondary">Not set</Text>}
          </Descriptions.Item>
          {config?.smsTailscaleDeviceName && (
            <Descriptions.Item label="Tailscale Device">
              <Text>{config.smsTailscaleDeviceName}</Text>
            </Descriptions.Item>
          )}
        </Descriptions>

        <div style={{ marginTop: 16 }}>
          {!wizardMode && (
            <Space>
              <Button
                icon={<SettingOutlined />}
                onClick={() => { setWizardMode(true); setCurrentStep(0); setSaved(false); setTestResult(null); }}
              >
                {status?.configured ? 'Reconfigure' : 'Setup'}
              </Button>
              {status?.connected && (
                <>
                  <Button onClick={() => navigate('/app/sms')}>SMS Dashboard</Button>
                  <Button onClick={() => navigate('/app/sms/campaigns')}>Campaigns</Button>
                  <Button onClick={() => navigate('/app/sms/conversations')}>Conversations</Button>
                </>
              )}
            </Space>
          )}
        </div>
      </Card>

      {/* Setup Wizard */}
      {wizardMode && (
        <Card title={<><RocketOutlined /> SMS Setup Wizard</>}>
          <Steps
            current={currentStep}
            size={isMobile ? 'small' : 'default'}
            style={{ marginBottom: 24 }}
            items={[
              { title: 'Prepare Phone' },
              { title: 'Connect' },
              { title: 'Test & Save' },
            ]}
          />

          {/* Step 0: Phone Preparation */}
          {currentStep === 0 && (
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              {/* RCS Warning */}
              <Alert
                type="warning"
                showIcon
                message="Disable RCS / Chat Features"
                description={
                  <div>
                    <Paragraph style={{ marginBottom: 4 }}>
                      On the SMS phone, open <Text strong>Google Messages</Text> → <Text strong>Settings</Text> → <Text strong>Chat features</Text> → <Text strong>Turn off</Text>.
                    </Paragraph>
                    <Paragraph type="secondary" style={{ marginBottom: 0 }}>
                      This ensures all messages use plain SMS. If RCS (Rich Communication Services) is enabled, some replies may be sent via
                      data/Wi-Fi instead of the carrier SMS channel, which means the Termux server will never see them.
                    </Paragraph>
                  </div>
                }
              />

              {/* Part 1: Install F-Droid Apps */}
              <Alert
                type="error"
                showIcon
                icon={<AndroidOutlined />}
                message="Step 1 — Install Apps from F-Droid"
                description={
                  <div>
                    <Paragraph>
                      <Text strong style={{ fontSize: 14 }}>
                        Both Termux and Termux:API MUST be installed from F-Droid — not the Play Store.
                      </Text>
                      <br />
                      <Text type="secondary">
                        The Play Store version of Termux is abandoned and incompatible with the API plugin.
                        If you have Termux from the Play Store, uninstall it first.
                      </Text>
                    </Paragraph>
                    <ol style={{ marginLeft: 20, lineHeight: 2.4 }}>
                      <li>
                        <Text strong>Termux</Text> — terminal emulator for Android
                        <br /><Text type="secondary">Install from <Text strong>F-Droid</Text> (f-droid.org)</Text>
                      </li>
                      <li>
                        <Text strong>Termux:API</Text> — gives Termux access to SMS, contacts, battery
                        <br /><Text type="secondary">Also from <Text strong>F-Droid</Text>. Must be same source as Termux.</Text>
                      </li>
                      <li>
                        <Text strong>Termux:Boot</Text> (recommended) — auto-start server on phone reboot
                        <br /><Text type="secondary">Also from <Text strong>F-Droid</Text>. Open once after install to register.</Text>
                      </li>
                      <li>
                        <Text strong>Tailscale</Text> (recommended) — VPN mesh for stable IP addressing
                        <br /><Text type="secondary">Install from Play Store. Creates a persistent 100.x.x.x IP that works across networks.</Text>
                      </li>
                    </ol>
                  </div>
                }
              />

              {/* Part 2: Generate API Key */}
              <Divider>Step 2 — Generate API Key</Divider>
              <Paragraph>
                Generate a shared secret key. This key authenticates all communication between the server and the phone.
                <Text strong> All phone API endpoints require this key</Text> — including health checks.
              </Paragraph>

              <Space>
                <Button
                  type="primary"
                  icon={<ThunderboltOutlined />}
                  loading={generatingKey}
                  onClick={handleGenerateKey}
                >
                  Generate API Key
                </Button>
              </Space>

              {generatedKey && (
                <Alert
                  type="success"
                  showIcon
                  message="API Key Generated"
                  description={
                    <div>
                      <Space style={{ marginBottom: 8 }}>
                        <Button
                          size="small"
                          icon={showGeneratedKey ? <EyeInvisibleOutlined /> : <EyeOutlined />}
                          onClick={() => setShowGeneratedKey(!showGeneratedKey)}
                        >
                          {showGeneratedKey ? 'Hide' : 'Show'}
                        </Button>
                        <Button
                          size="small"
                          icon={<CopyOutlined />}
                          onClick={() => {
                            navigator.clipboard.writeText(generatedKey);
                            message.success('Copied to clipboard');
                          }}
                        >
                          Copy Key
                        </Button>
                      </Space>

                      {showGeneratedKey && (
                        <pre style={{ background: 'rgba(0,0,0,0.2)', padding: 12, borderRadius: 6, fontSize: 12, wordBreak: 'break-all' }}>
                          {generatedKey}
                        </pre>
                      )}
                    </div>
                  }
                />
              )}

              {/* Part 3: Run setup script */}
              {generatedKey && (
                <Alert
                  type="info"
                  showIcon
                  icon={<RocketOutlined />}
                  message="Step 3 — Run Setup on Phone"
                  description={
                    <div>
                      <Paragraph>
                        Open <Text strong>Termux</Text> on the phone and run these two commands.
                        The setup script handles everything: installs packages, saves the key, requests permissions,
                        configures auto-start, and launches the server.
                      </Paragraph>
                      <div style={{ background: 'rgba(0,0,0,0.1)', padding: 12, borderRadius: 6 }}>
                        <CmdLine comment="Clone the SMS server (first time only)" cmd="pkg install -y git && git clone --depth 1 --filter=blob:none --sparse https://gitea.bnkops.com/admin/changemaker.lite.git ~/sms-server && cd ~/sms-server && git sparse-checkout set termux-sms" />
                        <CmdLine comment="Run the setup script with your API key" cmd={`bash ~/sms-server/termux-sms/setup.sh ${generatedKey}`} />
                      </div>
                      <Paragraph style={{ marginTop: 12 }}>
                        The script will:
                      </Paragraph>
                      <ul style={{ marginLeft: 20, lineHeight: 2 }}>
                        <li>Install Python, Flask, and termux-api</li>
                        <li>Save the API key to ~/.bashrc and ~/.sms-api-key</li>
                        <li>Request SMS and Contacts permissions (tap <Text strong>Allow</Text>)</li>
                        <li>Set up Termux:Boot auto-start (if installed)</li>
                        <li>Install runit service supervisor and start the server</li>
                      </ul>
                      <Paragraph style={{ marginTop: 8 }}>
                        When done, note the <Text strong>Phone URL</Text> displayed (e.g. <Text code>http://100.x.x.x:5001</Text>) — you'll need it in the next step.
                      </Paragraph>
                    </div>
                  }
                />
              )}

              {/* Android hardening */}
              {generatedKey && (
                <Alert
                  type="warning"
                  showIcon
                  icon={<WarningOutlined />}
                  message="Prevent Android from Killing the Server"
                  description={
                    <div>
                      <Paragraph style={{ marginBottom: 4 }}>
                        Android aggressively kills background processes. To keep the SMS server running:
                      </Paragraph>
                      <ol style={{ marginLeft: 20, lineHeight: 2 }}>
                        <li><Text strong>Disable battery optimization</Text> for Termux, Termux:API, and Tailscale — Android Settings → Apps → [App] → Battery → Unrestricted</li>
                        <li><Text strong>Run wake lock</Text> in Termux: <Text code copyable>termux-wake-lock</Text></li>
                        <li><Text strong>Lock Termux in recents</Text> — long-press the Termux card in the app switcher and tap the lock icon</li>
                      </ol>
                    </div>
                  }
                />
              )}

              {/* Already set up? */}
              {generatedKey && (
                <Alert
                  type="info"
                  showIcon
                  icon={<KeyOutlined />}
                  message="Already have the server running?"
                  description={
                    <div>
                      <Paragraph style={{ marginBottom: 4 }}>If the server is already running but the API key needs updating, run this on the phone:</Paragraph>
                      <div style={{ background: 'rgba(0,0,0,0.1)', padding: 12, borderRadius: 6 }}>
                        <CmdLine comment="Update key and restart service" cmd={`sed -i '/SMS_API_SECRET/d' ~/.bashrc && echo 'export SMS_API_SECRET="${generatedKey}"' >> ~/.bashrc && source ~/.bashrc && sv restart sms-api`} />
                      </div>
                      <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
                        If <Text code>sv</Text> is not installed yet, run the full setup: <Text code copyable={{ text: `cd ~/sms-server && git pull && bash termux-sms/setup-services.sh` }}>cd ~/sms-server && git pull && bash termux-sms/setup-services.sh</Text>
                      </Paragraph>
                    </div>
                  }
                />
              )}

              <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end' }}>
                <Button type="primary" onClick={() => setCurrentStep(1)}>
                  Next: Connect to Phone
                </Button>
              </div>
            </Space>
          )}

          {/* Step 1: Connect to Phone */}
          {currentStep === 1 && (
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <Form.Item label="Connection Method" style={{ marginBottom: 0 }}>
                <Select
                  value={connectionMethod}
                  onChange={setConnectionMethod}
                  style={{ maxWidth: 300 }}
                  options={[
                    { value: 'tailscale', label: 'Tailscale Auto-Discovery (Recommended)' },
                    { value: 'manual', label: 'Manual URL Entry' },
                  ]}
                />
              </Form.Item>

              {connectionMethod === 'tailscale' && (
                <>
                  <Alert
                    type="info"
                    showIcon
                    icon={<CloudServerOutlined />}
                    message="Tailscale Auto-Discovery"
                    description="Enter your Tailscale API key to automatically discover your phone's stable IP address. The phone must have Tailscale installed and connected."
                  />

                  <div style={{ maxWidth: 500 }}>
                    <Form layout="vertical">
                      <Form.Item label="Tailscale API Key">
                        <Input.Password
                          value={tailscaleApiKey}
                          onChange={e => setTailscaleApiKey(e.target.value)}
                          placeholder="tskey-api-..."
                          prefix={<ApiOutlined />}
                        />
                      </Form.Item>
                      <Form.Item label="Tailnet (optional)" tooltip="Leave empty for default tailnet. Usually your-org.ts.net.">
                        <Input
                          value={tailscaleTailnet}
                          onChange={e => setTailscaleTailnet(e.target.value)}
                          placeholder="your-org.ts.net (leave empty for default)"
                        />
                      </Form.Item>
                      <Form.Item>
                        <Button
                          type="primary"
                          icon={<WifiOutlined />}
                          loading={discoveringDevices}
                          onClick={handleDiscoverDevices}
                          disabled={!tailscaleApiKey}
                        >
                          Discover Devices
                        </Button>
                      </Form.Item>
                    </Form>
                  </div>

                  {devices.length > 0 && (
                    <div>
                      <Paragraph strong>Select Your Phone:</Paragraph>
                      <Select
                        value={selectedDevice}
                        onChange={handleDeviceSelect}
                        style={{ width: '100%', maxWidth: 500 }}
                        placeholder="Select a device..."
                        optionLabelProp="label"
                      >
                        {devices.map(device => {
                          const ipv4 = device.addresses.find(a => !a.includes(':')) || device.addresses[0] || '';
                          const isAndroid = device.os.toLowerCase() === 'android';
                          return (
                            <Select.Option
                              key={device.id}
                              value={device.id}
                              label={`${device.hostname} (${ipv4})`}
                            >
                              <Space>
                                {isAndroid
                                  ? <AndroidOutlined style={{ color: '#a4c639' }} />
                                  : <CloudServerOutlined />}
                                <Text strong>{device.hostname}</Text>
                                <Tag color={isAndroid ? 'green' : 'default'}>{device.os}</Tag>
                                <Text type="secondary">{ipv4}</Text>
                                <Tag color={device.online ? 'success' : 'default'}>
                                  {device.online ? 'Online' : 'Offline'}
                                </Tag>
                              </Space>
                            </Select.Option>
                          );
                        })}
                      </Select>
                    </div>
                  )}
                </>
              )}

              {connectionMethod === 'manual' && (
                <Alert
                  type="info"
                  showIcon
                  icon={<LinkOutlined />}
                  message="Manual Entry"
                  description="Enter the Termux API server URL directly. If using Tailscale, the IP is typically 100.x.x.x."
                />
              )}

              <Divider>Termux Connection</Divider>

              <div style={{ maxWidth: 500 }}>
                <Form layout="vertical">
                  <Form.Item label="Termux API URL" required>
                    <Input
                      value={termuxUrl}
                      onChange={e => setTermuxUrl(e.target.value)}
                      placeholder="http://100.x.x.x:5001"
                      prefix={<LinkOutlined />}
                    />
                  </Form.Item>
                  <Form.Item
                    label="Termux API Key"
                    required
                    help="Must match the SMS_API_SECRET on the phone. If you generated a key in Step 1, it's pre-filled."
                  >
                    <Input.Password
                      value={termuxApiKey}
                      onChange={e => setTermuxApiKey(e.target.value)}
                      placeholder={generatedKey ? 'Pre-filled from generated key' : 'Paste your API key'}
                      prefix={<ApiOutlined />}
                    />
                  </Form.Item>
                </Form>
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16 }}>
                <Button onClick={() => setCurrentStep(0)}>Back</Button>
                <Button
                  type="primary"
                  onClick={() => setCurrentStep(2)}
                  disabled={!termuxUrl || !termuxApiKey}
                >
                  Next: Test Connection
                </Button>
              </div>
            </Space>
          )}

          {/* Step 2: Test & Save */}
          {currentStep === 2 && (
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <Descriptions column={1} bordered size="small" title="Configuration Summary">
                <Descriptions.Item label="Termux URL">
                  <Text code>{termuxUrl}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="API Key">
                  <Text code>{'••••••••' + termuxApiKey.slice(-8)}</Text>
                </Descriptions.Item>
                {tailscaleApiKey && (
                  <Descriptions.Item label="Tailscale">
                    <Tag icon={<CheckCircleOutlined />} color="success">Configured</Tag>
                  </Descriptions.Item>
                )}
                {selectedDevice && devices.find(d => d.id === selectedDevice) && (
                  <Descriptions.Item label="Device">
                    <Text>{devices.find(d => d.id === selectedDevice)?.hostname}</Text>
                  </Descriptions.Item>
                )}
              </Descriptions>

              <Alert
                type="info"
                showIcon
                message="Connection test verifies both reachability and API key authentication"
                description="The test calls the phone's health endpoint with your API key. If the key doesn't match what the phone has, the test will fail with an authentication error."
              />

              <Space>
                <Button
                  type="primary"
                  icon={<WifiOutlined />}
                  loading={testing}
                  onClick={handleTestConnection}
                >
                  Test Connection
                </Button>
                {testResult && (
                  <Button icon={<ReloadOutlined />} onClick={() => setTestResult(null)}>
                    Reset
                  </Button>
                )}
              </Space>

              {testResult && (
                testResult.success ? (
                  <>
                    <Alert
                      type="success"
                      showIcon
                      message="Connection Successful — Phone Authenticated!"
                      description={
                        <div>
                          <Paragraph type="secondary" style={{ marginBottom: 8 }}>
                            The phone is reachable and the API key is valid.
                          </Paragraph>
                          {testResult.health && (
                            <Descriptions column={{ xs: 1, sm: 2 }} size="small" bordered>
                              <Descriptions.Item label="Status">{testResult.health.status}</Descriptions.Item>
                              <Descriptions.Item label="Uptime">{Math.round(testResult.health.uptime / 60)}m</Descriptions.Item>
                              <Descriptions.Item label="Messages Sent">{testResult.health.messages_sent}</Descriptions.Item>
                            </Descriptions>
                          )}
                        </div>
                      }
                    />
                    <Card size="small" title={<><SendOutlined /> Send Test SMS</>}>
                      <Space>
                        <Input
                          value={testPhone}
                          onChange={(e) => setTestPhone(e.target.value)}
                          placeholder="+1 555 123 4567"
                          prefix={<PhoneOutlined />}
                          style={{ width: 220 }}
                        />
                        <Button
                          type="primary"
                          icon={<SendOutlined />}
                          loading={testSending}
                          onClick={handleSendTest}
                          disabled={!testPhone.trim()}
                        >
                          Send Test SMS
                        </Button>
                      </Space>
                      <div style={{ marginTop: 8 }}>
                        <Text type="secondary">Sends "Test SMS from Changemaker" to the number above.</Text>
                      </div>
                    </Card>
                  </>
                ) : (
                  <Alert
                    type="error"
                    showIcon
                    message="Connection Failed"
                    description={
                      <div>
                        <Paragraph>{testResult.error}</Paragraph>
                        {testResult.error?.includes('401') || testResult.error?.includes('Authentication') ? (
                          <Paragraph>
                            <Text strong type="danger">API key mismatch.</Text>{' '}
                            The key entered here does not match the phone's <Text code>SMS_API_SECRET</Text>.
                            Go back to Step 1 and re-run the setup script with the generated key, or update the key on the phone:
                          </Paragraph>
                        ) : (
                          <Paragraph type="secondary">
                            Make sure the Termux SMS server is running on the phone, the URL is correct, and the phone is accessible on the network.
                          </Paragraph>
                        )}
                      </div>
                    }
                  />
                )
              )}

              {saved ? (
                <Result
                  status="success"
                  title="SMS Configuration Saved!"
                  subTitle="Your phone is connected and SMS features are enabled."
                  extra={[
                    <Button key="dashboard" type="primary" onClick={() => navigate('/app/sms')}>
                      Go to SMS Dashboard
                    </Button>,
                    <Button key="close" onClick={() => { setWizardMode(false); setSaved(false); }}>
                      Close Wizard
                    </Button>,
                  ]}
                />
              ) : (
                <>
                  <Divider />
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Button onClick={() => setCurrentStep(1)}>Back</Button>
                    <Button
                      type="primary"
                      size="large"
                      icon={<CheckCircleOutlined />}
                      loading={saving}
                      disabled={!testResult?.success}
                      onClick={handleSaveConfig}
                    >
                      Save Configuration
                    </Button>
                  </div>
                </>
              )}
            </Space>
          )}

          {/* Cancel button */}
          {!saved && (
            <div style={{ marginTop: 24, textAlign: 'center' }}>
              <Button type="link" onClick={() => { setWizardMode(false); setCurrentStep(0); }}>
                Cancel Setup
              </Button>
            </div>
          )}
        </Card>
      )}

      {/* Connected Dashboard — when configured + connected, not in wizard */}
      {!wizardMode && status?.configured && status?.connected && (
        <Card title={<><CheckCircleOutlined style={{ color: '#52c41a' }} /> Phone Connected</>}>
          <Alert
            type="success"
            showIcon
            message="SMS System Active"
            description="Your Android phone is connected and ready to send/receive SMS messages."
            style={{ marginBottom: 16 }}
          />

          <Space wrap style={{ marginBottom: 16 }}>
            <Button type="primary" icon={<PhoneOutlined />} onClick={() => navigate('/app/sms')}>
              SMS Dashboard
            </Button>
            <Button icon={<SendOutlined />} onClick={() => navigate('/app/sms/campaigns')}>
              Campaigns
            </Button>
            <Button icon={<MessageOutlined />} onClick={() => navigate('/app/sms/conversations')}>
              Conversations
            </Button>
          </Space>

          <Divider style={{ margin: '12px 0' }} />
          <Text strong>Send Test SMS</Text>
          <div style={{ marginTop: 8 }}>
            <Space>
              <Input
                value={testPhone}
                onChange={(e) => setTestPhone(e.target.value)}
                placeholder="+1 555 123 4567"
                prefix={<PhoneOutlined />}
                style={{ width: 220 }}
              />
              <Button
                icon={<SendOutlined />}
                loading={testSending}
                onClick={handleSendTest}
                disabled={!testPhone.trim()}
              >
                Send Test SMS
              </Button>
            </Space>
          </div>
        </Card>
      )}

      {/* Warning when configured but disconnected */}
      {!wizardMode && status?.configured && !status?.connected && (
        <Alert
          type="warning"
          showIcon
          message="Phone Disconnected"
          description={
            <div>
              <Paragraph style={{ marginBottom: 8 }}>
                The Termux API server is not responding. This can mean:
              </Paragraph>
              <ul style={{ marginLeft: 20, marginBottom: 8 }}>
                <li><Text strong>Server not running</Text> — Android may have killed the Termux process. Open Termux on the phone and check: <Text code>sv status sms-api</Text>. If down, run: <Text code>sv up sms-api</Text></li>
                <li><Text strong>API key mismatch</Text> — the key saved here doesn't match the phone's <Text code>SMS_API_SECRET</Text>. Click Reconfigure to generate a new key and update both sides.</li>
                <li><Text strong>Network issue</Text> — the phone may not be reachable. Check Tailscale is connected on the phone.</li>
              </ul>
            </div>
          }
          action={
            <Space direction="vertical" size="small">
              <Button size="small" icon={<ReloadOutlined />} onClick={fetchStatus}>
                Retry
              </Button>
            </Space>
          }
        />
      )}
    </Space>
  );
}
