'use client';

import { useState } from 'react';
import {
  Smartphone,
  Server,
  Wifi,
  Globe,
  ArrowRight,
  ArrowLeft,
  CheckCircle2,
  XCircle,
  ChevronDown,
  ChevronUp,
  RefreshCw,
  Send,
  Download,
  Phone,
  WifiOff,
  Shield,
  BatteryCharging,
} from 'lucide-react';
import { useRouter } from 'next/navigation';

const steps = [
  { num: 1, title: 'Choose Method', description: 'Select how to connect your Android phone' },
  { num: 2, title: 'Install App', description: 'Download and set up SMS Gateway for Android' },
  { num: 3, title: 'Connect', description: 'Enter connection details and test' },
  { num: 4, title: 'Test SMS', description: 'Send a test message to verify' },
  { num: 5, title: 'Done!', description: 'Your phone is connected and ready' },
];

export default function ConnectPhonePage() {
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [mode, setMode] = useState('local');
  const [connectionDetails, setConnectionDetails] = useState({
    host: '',
    port: '8080',
    username: '',
    password: '',
    label: 'My Android Phone',
    apiUrl: '',
  });
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState({});
  const [sendingTest, setSendingTest] = useState(false);
  const [testMessage, setTestMessage] = useState({
    to: '',
    text: 'Hello from CloseBot SMS! Your Android gateway is working.',
  });
  const [connected, setConnected] = useState(false);
  const [troubleshootingOpen, setTroubleshootingOpen] = useState(false);
  const [expandedTroubleshoot, setExpandedTroubleshoot] = useState(null);

  const nextStep = () => setStep((s) => s + 1);
  const prevStep = () => setStep((s) => s - 1);

  const testConnection = async () => {
    setTesting(true);
    setTestResult({});
    try {
      const endpoint = mode === 'cloud' ? connectionDetails.apiUrl : `http://${connectionDetails.host}:${connectionDetails.port}`;
      const res = await fetch('/api/phone-gateway/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          host: connectionDetails.host,
          port: parseInt(connectionDetails.port),
          username: connectionDetails.username,
          password: connectionDetails.password,
          apiUrl: connectionDetails.apiUrl,
        }),
      });
      const data = await res.json();
      setTestResult(data);
      if (data.success) setConnected(true);
    } catch (err) {
      setTestResult({ success: false, error: 'Connection failed. Please check your details.' });
    } finally {
      setTesting(false);
    }
  };

  const sendTestSms = async () => {
    setSendingTest(true);
    try {
      const res = await fetch('/api/phone-gateway/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          host: connectionDetails.host,
          port: parseInt(connectionDetails.port),
          username: connectionDetails.username,
          password: connectionDetails.password,
          to: testMessage.to,
          message: testMessage.text,
        }),
      });
      const data = await res.json();
      if (data.success) {
        alert('Test message sent successfully!');
      } else {
        alert(`Failed to send: ${data.error}`);
      }
    } catch (err) {
      alert('Failed to send message. Please check your connection.');
    } finally {
      setSendingTest(false);
    }
  };

  const troubleshootingItems = [
    {
      id: 1,
      title: '"Connection refused" or "Can\'t connect to phone"',
      solutions: [
        'Make sure your phone and this server are on the same WiFi network',
        'Check that SMS Gateway app is running and Local Server is toggled ON',
        'Try disabling your phone\'s mobile data temporarily',
        'Check if a firewall or VPN is blocking local network connections',
        'Verify that IP address hasn\'t changed (phones can get new IPs)',
      ],
      icon: WifiOff,
    },
    {
      id: 2,
      title: '"SMS not sending" or "Message stuck in pending"',
      solutions: [
        'Check that you granted SMS permission to SMS Gateway app',
        'Make sure your phone has cellular signal',
        'Check if your carrier is blocking bulk SMS (some carriers limit to ~100/day)',
        'Try restarting the SMS Gateway app',
        'Check your phone\'s SMS outbox for stuck messages',
      ],
      icon: Send,
    },
    {
      id: 3,
      title: '"App keeps stopping" or "Gateway goes offline"',
      solutions: [
        'Disable battery optimization for SMS Gateway app (Settings > Battery > SMS Gateway > Don\'t optimize)',
        'On Samsung: also disable "Put app to sleep" in Device Care',
        'On Xiaomi: enable "Autostart" for the app',
        'On Huawei: add to "Protected Apps"',
        'Keep the app in recent apps, don\'t swipe it away',
        'Consider enabling "Start on boot" option in the app',
      ],
      icon: BatteryCharging,
    },
    {
      id: 4,
      title: '"Phone IP address keeps changing"',
      solutions: [
        'Set a static IP on your phone (Settings > WiFi > your network > IP settings > Static)',
        'Or set a DHCP reservation on your router for your phone\'s MAC address',
        'The app shows your current IP — update it here if it changes',
      ],
      icon: RefreshCw,
    },
    {
      id: 5,
      title: '"Messages showing as sent but not received"',
      solutions: [
        'The carrier may be filtering messages — try different message content',
        'Check if the recipient has blocked your number',
        'Some carriers require A2P registration even for phone-originated SMS in bulk',
        'Try sending to a different number to isolate the issue',
      ],
      icon: Phone,
    },
    {
      id: 6,
      title: '"Can\'t install APK"',
      solutions: [
        'Go to Settings > Security (or Privacy on some devices) > enable "Unknown Sources"',
        'On Android 8+: you need to grant install permission to your browser or file manager',
        'Make sure you downloaded the correct APK for your device (ARM vs x86)',
      ],
      icon: Download,
    },
  ];

  return (
    <div className="min-h-screen bg-[#0f1729] text-slate-200">
      <div className="ml-[240px] min-h-screen">
        <div className="border-b border-slate-800/60 px-6 py-4">
          <h1 className="text-2xl font-bold text-white">Connect Your Android Phone</h1>
          <p className="text-sm text-slate-500 mt-0.5">
            Turn your Android phone into a free SMS gateway — no Twilio fees
          </p>
        </div>

        <div className="p-6 lg:p-8 max-w-5xl mx-auto">
          <div className="flex items-center justify-between mb-8">
            {steps.map((s) => (
              <div key={s.num} className="flex items-center flex-1">
                <div className={`flex flex-col items-center justify-center w-10 h-10 rounded-full border-2 transition-all duration-200 ${step >= s.num ? 'bg-cyan-500 border-cyan-500 text-white' : 'bg-slate-800 border-slate-700 text-slate-500'} ${step > s.num ? 'ring-2 ring-cyan-500 ring-offset-2 ring-offset-slate-900' : ''}`}>
                  {step > s.num ? <CheckCircle2 className="w-5 h-5" /> : <span className="text-sm font-semibold">{s.num}</span>}
                </div>
                {s.num < 5 && (
                  <div className={`flex-1 h-0.5 ${step < s.num ? 'bg-cyan-500' : 'bg-slate-800'}`}></div>
                )}
              </div>
            ))}
          </div>

          <div className="card p-6 lg:p-8">
            {step === 1 && (
              <div className="space-y-6">
                <h2 className="text-xl font-bold text-white mb-4">Choose Connection Method</h2>

                <div className="grid md:grid-cols-2 gap-4">
                  <div
                    className={`card cursor-pointer border-2 transition-all duration-200 ${mode === 'local' ? 'border-cyan-500 bg-cyan-500/10' : 'border-slate-700/50 hover:border-slate-600'}`}
                    onClick={() => setMode('local')}
                  >
                    <div className="flex items-center gap-4 mb-3">
                      <div className="p-3 rounded-lg bg-cyan-500/20">
                        <Wifi className="w-6 h-6 text-cyan-400" />
                      </div>
                      <div>
                        <h3 className="font-semibold text-white">Local Network</h3>
                        <p className="text-sm text-slate-400">Fastest and most private</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3 text-sm text-slate-400">
                      <Smartphone className="w-4 h-4" />
                      <ArrowRight className="w-4 h-4" />
                      <Server className="w-4 h-4" />
                    </div>
                    <p className="text-sm text-slate-400 mt-3">
                      Your phone and server must be on the same WiFi network. Zero cloud
                      relay required.
                    </p>
                  </div>

                  <div
                    className={`card cursor-pointer border-2 transition-all duration-200 ${mode === 'cloud' ? 'border-blue-500 bg-blue-500/10' : 'border-slate-700/50 hover:border-slate-600'}`}
                    onClick={() => setMode('cloud')}
                  >
                    <div className="flex items-center gap-4 mb-3">
                      <div className="p-3 rounded-lg bg-blue-500/20">
                        <Globe className="w-6 h-6 text-blue-400" />
                      </div>
                      <div>
                        <h3 className="font-semibold text-white">Cloud Relay</h3>
                        <p className="text-sm text-slate-400">Works from anywhere</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3 text-sm text-slate-400">
                      <Smartphone className="w-4 h-4" />
                      <ArrowRight className="w-4 h-4" />
                      <Globe className="w-4 h-4" />
                      <Server className="w-4 h-4" />
                    </div>
                    <p className="text-sm text-slate-400 mt-3">
                      Phone connects to cloud relay server. Works on any network,
                      even different from your server.
                    </p>
                  </div>
                </div>

                <button onClick={nextStep} className="w-full bg-cyan-500 text-white font-semibold py-3 rounded-lg hover:bg-cyan-600 transition-colors">
                  Continue to Install App
                  <ArrowRight className="inline w-4 h-4 ml-2" />
                </button>
              </div>
            )}

            {step === 2 && (
              <div className="space-y-6">
                <h2 className="text-xl font-bold text-white mb-4">Install SMS Gateway App</h2>

                <div className="flex justify-center mb-6">
                  <div className="w-64 h-32 rounded-2xl bg-gradient-to-br from-slate-800 to-slate-900 border-2 border-slate-700 flex items-center justify-center">
                    <div className="text-center">
                      <div className="w-20 h-20 bg-cyan-500/20 rounded-xl flex items-center justify-center mb-2">
                        <Smartphone className="w-10 h-10 text-cyan-400" />
                      </div>
                      <p className="text-xs text-slate-500 font-mono">SMS Gateway</p>
                    </div>
                  </div>
                </div>

                <a
                  href="https://github.com/capcom6/android-sms-gateway/releases"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="block w-full bg-cyan-500 text-white font-semibold py-4 rounded-lg hover:bg-cyan-600 transition-colors text-center"
                >
                  <Download className="inline w-4 h-4 mr-2" />
                  Download SMS Gateway for Android
                </a>

                <div className="space-y-3 mt-6">
                  <h3 className="font-semibold text-white mb-2">Installation Steps:</h3>
                  <div className="space-y-2">
                    {[
                      'Download and install APK (enable "Unknown Sources" in Security settings if needed)',
                      'Open app and grant SMS permissions',
                      'Toggle "Local Server" to ON',
                      'Note down IP address and credentials shown in the app',
                      'Keep app running in the background',
                    ].map((text, idx) => (
                      <div key={idx} className="flex items-start gap-3 p-3 rounded-lg bg-slate-800/50">
                        <div className="flex-shrink-0 w-6 h-6 rounded-full bg-cyan-500/20 flex items-center justify-center">
                          <span className="text-sm font-semibold text-cyan-400">{idx + 1}</span>
                        </div>
                        <p className="text-sm text-slate-300">{text}</p>
                      </div>
                    ))}
                  </div>
                </div>

                <details className="mt-4 text-sm text-slate-400">
                  <summary className="cursor-pointer text-cyan-400 hover:text-cyan-300">
                    Having trouble installing?
                  </summary>
                  <div className="mt-2 space-y-2 pl-4 border-l-2 border-slate-700">
                    <p>Make sure you downloaded the correct APK for your device (ARM vs x86)</p>
                    <p>On Android 8+: you may need to grant install permission from the browser</p>
                    <p>Some Samsung devices require you to tap "Install unknown apps" multiple times</p>
                  </div>
                </details>

                <div className="flex gap-3 mt-6">
                  <button onClick={prevStep} className="px-4 py-2 text-slate-400 hover:text-slate-300 transition-colors">
                    <ArrowLeft className="inline w-4 h-4 mr-1" />
                    Back
                  </button>
                  <button onClick={nextStep} className="flex-1 bg-cyan-500 text-white font-semibold py-2 rounded-lg hover:bg-cyan-600 transition-colors">
                    Continue to Connect
                    <ArrowRight className="inline w-4 h-4 ml-2" />
                  </button>
                </div>
              </div>
            )}

            {step === 3 && (
              <div className="space-y-6">
                <h2 className="text-xl font-bold text-white mb-4">Enter Connection Details</h2>

                {mode === 'local' ? (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">
                        Phone IP Address
                      </label>
                      <input
                        type="text"
                        placeholder="192.168.1.100"
                        value={connectionDetails.host}
                        onChange={(e) =>
                          setConnectionDetails({ ...connectionDetails, host: e.target.value })
                        }
                        className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg py-3 px-4 text-white placeholder-slate-500 focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-all"
                      />
                      <p className="text-xs text-slate-500 mt-1">
                        Shown in SMS Gateway app under Local Server
                      </p>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">
                        Port
                      </label>
                      <input
                        type="number"
                        placeholder="8080"
                        value={connectionDetails.port}
                        onChange={(e) =>
                          setConnectionDetails({ ...connectionDetails, port: e.target.value })
                        }
                        className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg py-3 px-4 text-white placeholder-slate-500 focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-all"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">
                        Username
                      </label>
                      <input
                        type="text"
                        placeholder="username"
                        value={connectionDetails.username}
                        onChange={(e) =>
                          setConnectionDetails({ ...connectionDetails, username: e.target.value })
                        }
                        className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg py-3 px-4 text-white placeholder-slate-500 focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-all"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">
                        Password
                      </label>
                      <input
                        type="password"
                        placeholder="password"
                        value={connectionDetails.password}
                        onChange={(e) =>
                          setConnectionDetails({ ...connectionDetails, password: e.target.value })
                        }
                        className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg py-3 px-4 text-white placeholder-slate-500 focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-all"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">
                        Phone Label
                      </label>
                      <input
                        type="text"
                        placeholder="e.g., Jake's Galaxy S24"
                        value={connectionDetails.label}
                        onChange={(e) =>
                          setConnectionDetails({ ...connectionDetails, label: e.target.value })
                        }
                        className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg py-3 px-4 text-white placeholder-slate-500 focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-all"
                      />
                    </div>
                  </div>
                ) : (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">
                        API URL
                      </label>
                      <input
                        type="text"
                        placeholder="https://api.sms-gate.app"
                        value={connectionDetails.apiUrl}
                        onChange={(e) =>
                          setConnectionDetails({ ...connectionDetails, apiUrl: e.target.value })
                        }
                        className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg py-3 px-4 text-white placeholder-slate-500 focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-all"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-slate-300 mb-2">
                        API Key
                      </label>
                      <input
                        type="text"
                        placeholder="your-api-key-from-app"
                        value={connectionDetails.username}
                        onChange={(e) =>
                          setConnectionDetails({ ...connectionDetails, username: e.target.value })
                        }
                        className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg py-3 px-4 text-white placeholder-slate-500 focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-all"
                      />
                    </div>
                  </div>
                )}

                <div className="flex items-center justify-between p-4 rounded-lg bg-slate-800/30 border border-slate-700/30 mt-6">
                  <div>
                    <p className="text-sm font-medium text-white">
                      Test if {mode === 'local' ? 'phone is reachable' : 'cloud API is accessible'}
                    </p>
                  </div>
                  <button
                    onClick={testConnection}
                    disabled={testing}
                    className={`flex items-center gap-2 bg-cyan-500 text-white font-semibold py-2 px-4 rounded-lg hover:bg-cyan-600 transition-colors ${testing ? 'opacity-50 cursor-not-allowed' : ''}`}
                  >
                    {testing ? (
                      <div className="w-4 h-4 border-2 border-white/30 border-t-transparent animate-spin rounded-full" />
                    ) : (
                      <CheckCircle2 className="w-4 h-4" />
                    )}
                    Test Connection
                  </button>
                </div>

                {testResult.success !== undefined && (
                  <div className={`flex items-center gap-3 p-4 rounded-lg border-2 mt-4 ${testResult.success ? 'border-green-500/30 bg-green-500/10' : 'border-red-500/30 bg-red-500/10'}`}>
                    {testResult.success ? (
                      <CheckCircle2 className="w-6 h-6 text-green-400" />
                    ) : (
                      <XCircle className="w-6 h-6 text-red-400" />
                    )}
                    <div>
                      <p className={`font-semibold ${testResult.success ? 'text-green-400' : 'text-red-400'}`}>
                        {testResult.success ? 'Connected!' : testResult.error}
                      </p>
                      {testResult.deviceInfo && (
                        <p className="text-xs text-slate-500 mt-1 font-mono">
                          Device: {testResult.deviceInfo.model || 'Unknown'} • Android{' '}
                          {testResult.deviceInfo.androidVersion || '?'}
                        </p>
                      )}
                    </div>
                  </div>
                )}

                <div className="flex gap-3 mt-6">
                  <button onClick={prevStep} className="px-4 py-2 text-slate-400 hover:text-slate-300 transition-colors">
                    <ArrowLeft className="inline w-4 h-4 mr-1" />
                    Back
                  </button>
                  <button
                    onClick={nextStep}
                    disabled={!connected}
                    className={`flex-1 bg-cyan-500 text-white font-semibold py-2 rounded-lg hover:bg-cyan-600 transition-colors ${!connected && 'opacity-50 cursor-not-allowed'}`}
                  >
                    Continue to Test SMS
                    <ArrowRight className="inline w-4 h-4 ml-2" />
                  </button>
                </div>

                <div className="mt-8 border-t border-slate-700/50 pt-6">
                  <button
                    onClick={() => setTroubleshootingOpen(!troubleshootingOpen)}
                    className="flex items-center gap-2 text-sm text-slate-400 hover:text-slate-300 transition-colors w-full"
                  >
                    <Shield className="w-4 h-4" />
                    {troubleshootingOpen ? (
                      <>
                        Hide Troubleshooting
                        <ChevronUp className="w-4 h-4" />
                      </>
                    ) : (
                      <>
                        Show Troubleshooting
                        <ChevronDown className="w-4 h-4" />
                      </>
                    )}
                  </button>

                  {troubleshootingOpen && (
                    <div className="mt-4 space-y-3">
                      {troubleshootingItems.map((item) => (
                        <details
                          key={item.id}
                          open={expandedTroubleshoot === item.id}
                          onToggle={() => setExpandedTroubleshoot(expandedTroubleshoot === item.id ? null : item.id)}
                          className="group"
                        >
                          <summary className="flex items-start gap-3 cursor-pointer p-4 rounded-lg bg-slate-800/30 hover:bg-slate-800/50 transition-colors">
                            <item.icon className="w-5 h-5 text-slate-400 flex-shrink-0" />
                            <div className="flex-1">
                              <p className="font-medium text-white">{item.title}</p>
                              <p className="text-xs text-slate-500">
                                {item.solutions.length} solutions
                              </p>
                            </div>
                            {expandedTroubleshoot === item.id ? (
                              <ChevronUp className="w-4 h-4 text-slate-500" />
                            ) : (
                              <ChevronDown className="w-4 h-4 text-slate-500" />
                            )}
                          </summary>
                          <div className={`mt-2 ml-8 space-y-2 text-sm text-slate-300 overflow-hidden transition-all ${expandedTroubleshoot === item.id ? 'max-h-96' : 'max-h-0'}`}>
                            {item.solutions.map((solution, idx) => (
                              <div key={idx} className="flex items-start gap-2">
                                <span className="text-cyan-400">•</span>
                                <p>{solution}</p>
                              </div>
                            ))}
                          </div>
                        </details>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            )}

            {step === 4 && (
              <div className="space-y-6">
                <h2 className="text-xl font-bold text-white mb-4">Test SMS</h2>

                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-slate-300 mb-2">
                      Phone Number to Send To
                    </label>
                    <input
                      type="tel"
                      placeholder="+15551234567"
                      value={testMessage.to}
                      onChange={(e) =>
                        setTestMessage({ ...testMessage, to: e.target.value })
                      }
                      className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg py-3 px-4 text-white placeholder-slate-500 focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-all"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-300 mb-2">
                      Test Message
                    </label>
                    <textarea
                      placeholder="Your message here..."
                      value={testMessage.text}
                      onChange={(e) =>
                        setTestMessage({ ...testMessage, text: e.target.value })
                      }
                      rows={3}
                      className="w-full bg-slate-800/50 border border-slate-700/50 rounded-lg py-3 px-4 text-white placeholder-slate-500 focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-all resize-none"
                    />
                  </div>
                </div>

                <button
                  onClick={sendTestSms}
                  disabled={sendingTest}
                  className={`w-full flex items-center justify-center gap-2 bg-cyan-500 text-white font-semibold py-3 rounded-lg hover:bg-cyan-600 transition-colors ${sendingTest ? 'opacity-50 cursor-not-allowed' : ''}`}
                >
                  {sendingTest ? (
                    <div className="w-4 h-4 border-2 border-white/30 border-t-transparent animate-spin rounded-full" />
                  ) : (
                    <Send className="w-4 h-4" />
                  )}
                  Send Test Message
                </button>

                {testResult.success && (
                  <div className="flex items-center gap-3 p-4 rounded-lg border border-green-500/30 bg-green-500/10 mt-4">
                    <CheckCircle2 className="w-6 h-6 text-green-400" />
                    <p className="font-semibold text-green-400">
                      Test message sent successfully!
                    </p>
                  </div>
                )}

                <div className="flex gap-3 mt-6">
                  <button onClick={prevStep} className="px-4 py-2 text-slate-400 hover:text-slate-300 transition-colors">
                    <ArrowLeft className="inline w-4 h-4 mr-1" />
                    Back
                  </button>
                  <button
                    onClick={nextStep}
                    disabled={!testResult.success}
                    className={`flex-1 bg-cyan-500 text-white font-semibold py-2 rounded-lg hover:bg-cyan-600 transition-colors ${!testResult.success && 'opacity-50 cursor-not-allowed'}`}
                  >
                    Finish
                    <CheckCircle2 className="inline w-4 h-4 ml-2" />
                  </button>
                </div>
              </div>
            )}

            {step === 5 && (
              <div className="space-y-6 text-center">
                <div className="flex justify-center mb-6">
                  <div className="w-24 h-24 rounded-full bg-green-500/20 flex items-center justify-center">
                    <CheckCircle2 className="w-12 h-12 text-green-400" />
                  </div>
                </div>

                <h2 className="text-2xl font-bold text-white mb-2">
                  Your phone is connected!
                </h2>
                <p className="text-slate-400 mb-6">
                  CloseBot SMS is now configured to send SMS through your Android phone.
                  Messages sent via the app will appear in your Dashboard and Conversations.
                </p>

                <div className="card p-6 max-w-md mx-auto text-left">
                  <div className="flex items-center gap-3 mb-4">
                    <Smartphone className="w-8 h-8 text-cyan-400" />
                    <div>
                      <p className="font-semibold text-white">{connectionDetails.label}</p>
                      <p className="text-sm text-slate-400 font-mono">
                        {mode === 'local' ? `${connectionDetails.host}:${connectionDetails.port}` : connectionDetails.apiUrl}
                      </p>
                    </div>
                  </div>
                  <div className="h-px bg-slate-700/30"></div>
                  <div className="space-y-3 mt-4 text-sm text-slate-400">
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-green-500" />
                      <p>Gateway is active and ready to send messages</p>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full bg-cyan-500" />
                      <p>{mode === 'local' ? 'Messages are free (no carrier fees)' : 'Using cloud relay for connectivity'}</p>
                    </div>
                  </div>
                </div>
              </div>

              <div className="rounded-lg bg-slate-800/30 border border-slate-700/30 p-4 mt-6">
                <h3 className="font-semibold text-white mb-2 flex items-center gap-2">
                  <Shield className="w-4 h-4 text-cyan-400" />
                  Keep these tips in mind:
                </h3>
                <ul className="space-y-2 text-sm text-slate-300">
                  <li className="flex items-start gap-2">
                    <div className="w-2 h-2 rounded-full bg-green-500" />
                    <p>Keep SMS Gateway app running in the background</p>
                  </li>
                  <li className="flex items-start gap-2">
                    <div className="w-2 h-2 rounded-full bg-cyan-500" />
                    <p>Don't close app or Android may kill it background service</p>
                  </li>
                  <li className="flex items-start gap-2">
                    <div className="w-2 h-2 rounded-full bg-green-500" />
                    <p>Make sure your phone has cellular signal</p>
                  </li>
                </ul>
              </div>

              <div className="flex flex-col gap-3 mt-6">
                <button
                  onClick={() => router.push('/')}
                  className="w-full bg-cyan-500 text-white font-semibold py-3 rounded-lg hover:bg-cyan-600 transition-colors"
                >
                  Go to Dashboard
                </button>
                <button
                  onClick={() => {
                    setStep(1);
                    setConnected(false);
                    setTestResult({});
                    setTestMessage({ to: '', text: 'Hello from CloseBot SMS! Your Android gateway is working.' });
                  }}
                  className="w-full text-slate-400 hover:text-slate-300 py-2 transition-colors"
                >
                  Connect Another Phone
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
