import { useState } from 'react';
import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { handleError } from '@/lib/errorHandler';
import { PdfSettingsSection } from '@/components/PdfSettingsSection';
import {
  Database,
  Trash2,
  Plus,
  RefreshCw,
  AlertTriangle,
  MessageSquare,
  QrCode,
  Phone,
  CheckCircle,
  XCircle,
  Loader2,
  Send,
  Unlink,
  Download,
  Settings,
  FileText,
  Upload,
  Palette,
  ExternalLink,
  Shield,
} from 'lucide-react';

interface Stats {
  vips: number;
  drivers: number;
  vehicles: number;
  events: number;
  flights: number;
  users: number;
}

interface SignalStatus {
  isConnected: boolean;
  isLinked: boolean;
  phoneNumber: string | null;
  error?: string;
}

interface MessageStats {
  total: number;
  inbound: number;
  outbound: number;
  unread: number;
  driversWithMessages: number;
}

export function AdminTools() {
  const queryClient = useQueryClient();
  const [isLoading, setIsLoading] = useState(false);

  // Signal state
  const [showQRCode, setShowQRCode] = useState(false);
  const [qrCodeData, setQrCodeData] = useState<string | null>(null);
  const [qrLoading, setQrLoading] = useState(false);
  const [registerPhone, setRegisterPhone] = useState('');
  const [verifyCode, setVerifyCode] = useState('');
  const [showRegister, setShowRegister] = useState(false);
  const [showVerify, setShowVerify] = useState(false);
  const [testMessage, setTestMessage] = useState('');
  const [testRecipient, setTestRecipient] = useState('');

  // CAPTCHA state
  const [showCaptcha, setShowCaptcha] = useState(false);
  const [captchaToken, setCaptchaToken] = useState('');
  const [captchaUrl, setCaptchaUrl] = useState('');

  // Signal status query
  const { data: signalStatus, isLoading: signalLoading, refetch: refetchSignal } = useQuery<SignalStatus>({
    queryKey: ['signal-status'],
    queryFn: async () => {
      const { data } = await api.get('/signal/status');
      return data;
    },
    refetchInterval: 30000, // Refetch every 30 seconds
  });

  // Message stats query
  const { data: messageStats, refetch: refetchMessageStats } = useQuery<MessageStats>({
    queryKey: ['signal-message-stats'],
    queryFn: async () => {
      const { data } = await api.get('/signal/messages/stats');
      return data;
    },
  });

  // Fetch current stats
  const { data: stats, refetch: refetchStats } = useQuery<Stats>({
    queryKey: ['admin-stats'],
    queryFn: async () => {
      const [vips, drivers, vehicles, events, flights, users] = await Promise.all([
        api.get('/vips'),
        api.get('/drivers'),
        api.get('/vehicles'),
        api.get('/events'),
        api.get('/flights'),
        api.get('/users'),
      ]);
      return {
        vips: vips.data.length,
        drivers: drivers.data.length,
        vehicles: vehicles.data.length,
        events: events.data.length,
        flights: flights.data.length,
        users: users.data.length,
      };
    },
  });

  // ============================================================
  // BULK SEED OPERATIONS (Fast - uses backend bulk endpoints)
  // ============================================================

  const handleGenerateAllData = async () => {
    if (!confirm('Generate complete test dataset? This will clear existing data and create VIPs, drivers, vehicles, flights, and events with dynamic times relative to NOW.')) {
      return;
    }

    setIsLoading(true);
    try {
      const { data } = await api.post('/seed/generate', { clearFirst: true });
      if (data.success) {
        queryClient.invalidateQueries();
        refetchStats();
        toast.success(`Generated all test data in ${data.elapsed}! Created ${data.created.vips} VIPs, ${data.created.drivers} drivers, ${data.created.vehicles} vehicles, ${data.created.flights} flights, ${data.created.events} events`);
      } else {
        toast.error(data.error || 'Failed to generate data');
      }
    } catch (error: any) {
      console.error('Failed to generate test data:', error);
      toast.error('Failed to generate: ' + (error.response?.data?.message || error.message));
    } finally {
      setIsLoading(false);
    }
  };

  const handleRegenerateEvents = async () => {
    if (!confirm('Regenerate all events with fresh times relative to NOW? This keeps existing VIPs, drivers, and vehicles but creates new dynamic events.')) {
      return;
    }

    setIsLoading(true);
    try {
      const { data } = await api.post('/seed/generate-events');
      if (data.success) {
        queryClient.invalidateQueries();
        refetchStats();
        toast.success(`Regenerated ${data.created.events} events in ${data.elapsed}!`);
      } else {
        toast.error(data.error || 'Failed to regenerate events');
      }
    } catch (error: any) {
      console.error('Failed to regenerate events:', error);
      toast.error('Failed to regenerate: ' + (error.response?.data?.message || error.message));
    } finally {
      setIsLoading(false);
    }
  };

  const handleClearAllData = async () => {
    if (!confirm('⚠️ DANGER: This will DELETE ALL data (VIPs, Drivers, Vehicles, Events, Flights, Messages). This cannot be undone. Are you absolutely sure?')) {
      return;
    }

    if (!confirm('Final confirmation: Delete EVERYTHING?')) {
      return;
    }

    setIsLoading(true);
    try {
      const { data } = await api.delete('/seed/clear');
      if (data.success) {
        queryClient.invalidateQueries();
        refetchStats();
        toast.success(`Cleared all data in ${data.elapsed}! Deleted ${data.deleted.vips} VIPs, ${data.deleted.drivers} drivers, ${data.deleted.vehicles} vehicles, ${data.deleted.events} events, ${data.deleted.flights} flights`);
      }
    } catch (error: any) {
      console.error('Failed to clear all data:', error);
      toast.error('Failed to clear: ' + (error.response?.data?.message || error.message));
    } finally {
      setIsLoading(false);
    }
  };

  // Signal handlers
  const handleGetQRCode = async () => {
    setQrLoading(true);
    try {
      const { data } = await api.get('/signal/qrcode');
      if (data.success && data.qrcode) {
        setQrCodeData(data.qrcode);
        setShowQRCode(true);
      } else {
        toast.error(data.message || 'Failed to get QR code');
      }
    } catch (error: any) {
      console.error('Failed to get QR code:', error);
      toast.error('Failed to get QR code: ' + (error.response?.data?.message || error.message));
    } finally {
      setQrLoading(false);
    }
  };

  const handleRegisterNumber = async (captcha?: string) => {
    if (!registerPhone) {
      toast.error('Please enter a phone number');
      return;
    }

    setIsLoading(true);
    try {
      const { data } = await api.post('/signal/register', {
        phoneNumber: registerPhone,
        captcha: captcha,
      });

      if (data.success) {
        toast.success(data.message);
        setShowRegister(false);
        setShowCaptcha(false);
        setCaptchaToken('');
        setShowVerify(true);
      } else if (data.captchaRequired) {
        // CAPTCHA is required - show the CAPTCHA modal
        setCaptchaUrl(data.captchaUrl || 'https://signalcaptchas.org/registration/generate.html');
        setShowCaptcha(true);
        toast.error('CAPTCHA verification required');
      } else {
        toast.error(data.message);
      }
    } catch (error: any) {
      console.error('Failed to register:', error);
      toast.error('Failed to register: ' + (error.response?.data?.message || error.message));
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmitCaptcha = async () => {
    if (!captchaToken) {
      toast.error('Please paste the CAPTCHA token');
      return;
    }

    // Clean up the token - extract just the token part if they pasted the full URL
    let token = captchaToken.trim();
    if (token.startsWith('signalcaptcha://')) {
      token = token.replace('signalcaptcha://', '');
    }

    // Retry registration with the captcha token
    await handleRegisterNumber(token);
  };

  const handleVerifyNumber = async () => {
    if (!verifyCode) {
      toast.error('Please enter the verification code');
      return;
    }

    setIsLoading(true);
    try {
      const { data } = await api.post('/signal/verify', {
        phoneNumber: registerPhone,
        code: verifyCode,
      });
      if (data.success) {
        toast.success(data.message);
        setShowVerify(false);
        setRegisterPhone('');
        setVerifyCode('');
        refetchSignal();
      } else {
        toast.error(data.message);
      }
    } catch (error: any) {
      console.error('Failed to verify:', error);
      toast.error('Failed to verify: ' + (error.response?.data?.message || error.message));
    } finally {
      setIsLoading(false);
    }
  };

  const handleUnlinkAccount = async () => {
    if (!signalStatus?.phoneNumber) return;

    if (!confirm(`Are you sure you want to unlink ${signalStatus.phoneNumber}? You will need to re-link to send messages.`)) {
      return;
    }

    setIsLoading(true);
    try {
      const { data } = await api.delete(`/signal/unlink/${encodeURIComponent(signalStatus.phoneNumber)}`);
      if (data.success) {
        toast.success('Account unlinked successfully');
        refetchSignal();
      } else {
        toast.error(data.message);
      }
    } catch (error: any) {
      console.error('Failed to unlink:', error);
      toast.error('Failed to unlink: ' + (error.response?.data?.message || error.message));
    } finally {
      setIsLoading(false);
    }
  };

  const handleSendTestMessage = async () => {
    if (!testRecipient || !testMessage) {
      toast.error('Please enter a recipient and message');
      return;
    }

    setIsLoading(true);
    try {
      const { data } = await api.post('/signal/send', {
        to: testRecipient,
        message: testMessage,
      });
      if (data.success) {
        toast.success('Message sent!');
        setTestMessage('');
      } else {
        toast.error(data.error || 'Failed to send message');
      }
    } catch (error: any) {
      console.error('Failed to send message:', error);
      toast.error('Failed to send: ' + (error.response?.data?.message || error.message));
    } finally {
      setIsLoading(false);
    }
  };

  const handleExportChats = async () => {
    try {
      const response = await api.get('/signal/messages/export', {
        responseType: 'blob',
      });

      // Create download link
      const blob = new Blob([response.data], { type: 'text/plain' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `signal-chats-${new Date().toISOString().split('T')[0]}.txt`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      toast.success('Chat export downloaded');
    } catch (error: any) {
      console.error('Failed to export chats:', error);
      toast.error('Failed to export: ' + (error.response?.data?.message || error.message));
    }
  };

  const handleDeleteAllChats = async () => {
    if (!confirm('Are you sure you want to delete ALL Signal chat messages? This cannot be undone.')) {
      return;
    }

    if (!confirm('Final confirmation: Delete all chat history?')) {
      return;
    }

    setIsLoading(true);
    try {
      const { data } = await api.delete('/signal/messages/all');
      if (data.success) {
        toast.success(`Deleted ${data.deleted} messages`);
        refetchMessageStats();
        queryClient.invalidateQueries({ queryKey: ['signal-messages'] });
        queryClient.invalidateQueries({ queryKey: ['signal-unread-counts'] });
      }
    } catch (error: any) {
      console.error('Failed to delete chats:', error);
      toast.error('Failed to delete: ' + (error.response?.data?.message || error.message));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      <h1 className="text-3xl font-bold text-foreground mb-2">Administrator Tools</h1>
      <p className="text-muted-foreground mb-8">Manage test data and database operations</p>

      {/* Current Database Stats */}
      <div className="bg-card border border-border shadow-soft rounded-lg p-6 mb-8 transition-colors">
        <div className="flex items-center mb-4">
          <Database className="h-5 w-5 text-muted-foreground mr-2" />
          <h2 className="text-lg font-medium text-foreground">Current Database Statistics</h2>
          <button
            onClick={() => refetchStats()}
            className="ml-auto text-sm text-primary hover:text-primary/80 transition-colors"
          >
            <RefreshCw className="h-4 w-4 inline mr-1" />
            Refresh
          </button>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
          <div className="text-center">
            <div className="text-3xl font-bold text-blue-600 dark:text-blue-400">{stats?.vips || 0}</div>
            <div className="text-sm text-muted-foreground">VIPs</div>
          </div>
          <div className="text-center">
            <div className="text-3xl font-bold text-green-600 dark:text-green-400">{stats?.drivers || 0}</div>
            <div className="text-sm text-muted-foreground">Drivers</div>
          </div>
          <div className="text-center">
            <div className="text-3xl font-bold text-orange-600 dark:text-orange-400">{stats?.vehicles || 0}</div>
            <div className="text-sm text-muted-foreground">Vehicles</div>
          </div>
          <div className="text-center">
            <div className="text-3xl font-bold text-purple-600 dark:text-purple-400">{stats?.events || 0}</div>
            <div className="text-sm text-muted-foreground">Events</div>
          </div>
          <div className="text-center">
            <div className="text-3xl font-bold text-indigo-600 dark:text-indigo-400">{stats?.flights || 0}</div>
            <div className="text-sm text-muted-foreground">Flights</div>
          </div>
          <div className="text-center">
            <div className="text-3xl font-bold text-yellow-600 dark:text-yellow-400">{stats?.users || 0}</div>
            <div className="text-sm text-muted-foreground">Users</div>
          </div>
        </div>
      </div>

      {/* PDF Customization Settings */}
      <PdfSettingsSection />

      {/* Signal Messaging Configuration */}
      <div className="bg-card border border-border shadow-soft rounded-lg p-6 mb-8 transition-colors">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center">
            <MessageSquare className="h-5 w-5 text-blue-600 mr-2" />
            <h2 className="text-lg font-medium text-foreground">Signal Messaging</h2>
          </div>
          <button
            onClick={() => refetchSignal()}
            className="text-sm text-primary hover:text-primary/80 transition-colors"
          >
            <RefreshCw className={`h-4 w-4 inline mr-1 ${signalLoading ? 'animate-spin' : ''}`} />
            Refresh
          </button>
        </div>

        {/* Connection Status */}
        <div className="mb-6 p-4 border border-border rounded-lg bg-muted/30">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              {signalLoading ? (
                <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
              ) : signalStatus?.isConnected ? (
                signalStatus?.isLinked ? (
                  <CheckCircle className="h-5 w-5 text-green-600" />
                ) : (
                  <XCircle className="h-5 w-5 text-yellow-600" />
                )
              ) : (
                <XCircle className="h-5 w-5 text-red-600" />
              )}
              <div>
                <p className="font-medium text-foreground">
                  {signalLoading
                    ? 'Checking status...'
                    : signalStatus?.isConnected
                    ? signalStatus?.isLinked
                      ? 'Connected & Linked'
                      : 'API Connected - Not Linked'
                    : 'Not Connected'}
                </p>
                {signalStatus?.phoneNumber && (
                  <p className="text-sm text-muted-foreground flex items-center gap-1">
                    <Phone className="h-3 w-3" />
                    {signalStatus.phoneNumber}
                  </p>
                )}
                {signalStatus?.error && (
                  <p className="text-sm text-red-600">{signalStatus.error}</p>
                )}
              </div>
            </div>

            {signalStatus?.isLinked && (
              <button
                onClick={handleUnlinkAccount}
                disabled={isLoading}
                className="inline-flex items-center px-3 py-2 border border-red-300 dark:border-red-700 text-sm font-medium rounded-md text-red-700 dark:text-red-400 bg-background hover:bg-red-50 dark:hover:bg-red-950/20 disabled:opacity-50 transition-colors"
              >
                <Unlink className="h-4 w-4 mr-1" />
                Unlink
              </button>
            )}
          </div>
        </div>

        {/* Link Account Section */}
        {signalStatus?.isConnected && !signalStatus?.isLinked && (
          <div className="mb-6 space-y-4">
            <p className="text-sm text-muted-foreground">
              Link your Signal account to send messages to drivers. You can either scan a QR code with your phone or register a phone number.
            </p>

            <div className="flex gap-3">
              <button
                onClick={handleGetQRCode}
                disabled={qrLoading || isLoading}
                className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 transition-colors"
              >
                {qrLoading ? (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                ) : (
                  <QrCode className="h-4 w-4 mr-2" />
                )}
                Link via QR Code
              </button>

              <button
                onClick={() => setShowRegister(true)}
                disabled={isLoading}
                className="inline-flex items-center px-4 py-2 border border-input text-foreground rounded-md hover:bg-accent disabled:opacity-50 transition-colors"
              >
                <Phone className="h-4 w-4 mr-2" />
                Register Phone Number
              </button>
            </div>
          </div>
        )}

        {/* QR Code Display */}
        {showQRCode && qrCodeData && (
          <div className="mb-6 p-4 border border-border rounded-lg bg-white dark:bg-gray-900 text-center">
            <h3 className="font-medium text-foreground mb-3">Scan with Signal App</h3>
            <div className="inline-block p-4 bg-white rounded-lg">
              <img
                src={`data:image/png;base64,${qrCodeData}`}
                alt="Signal QR Code"
                className="w-64 h-64"
              />
            </div>
            <p className="text-sm text-muted-foreground mt-3">
              Open Signal on your phone → Settings → Linked Devices → Link New Device
            </p>
            <button
              onClick={() => {
                setShowQRCode(false);
                setQrCodeData(null);
                refetchSignal();
              }}
              className="mt-3 text-sm text-primary hover:underline"
            >
              Done / Close
            </button>
          </div>
        )}

        {/* Register Phone Number */}
        {showRegister && !showCaptcha && (
          <div className="mb-6 p-4 border border-border rounded-lg">
            <h3 className="font-medium text-foreground mb-3">Register Phone Number</h3>
            <div className="flex gap-3">
              <input
                type="tel"
                value={registerPhone}
                onChange={(e) => setRegisterPhone(e.target.value)}
                placeholder="+1234567890"
                className="flex-1 px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              />
              <button
                onClick={() => handleRegisterNumber()}
                disabled={isLoading || !registerPhone}
                className="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 disabled:opacity-50"
              >
                {isLoading ? 'Sending...' : 'Send Code'}
              </button>
              <button
                onClick={() => {
                  setShowRegister(false);
                  setRegisterPhone('');
                }}
                className="px-4 py-2 border border-input text-foreground rounded-md hover:bg-accent"
              >
                Cancel
              </button>
            </div>
          </div>
        )}

        {/* CAPTCHA Challenge Modal */}
        {showCaptcha && (
          <div className="mb-6 p-4 border-2 border-yellow-400 dark:border-yellow-600 rounded-lg bg-yellow-50 dark:bg-yellow-950/20">
            <div className="flex items-center gap-2 mb-3">
              <Shield className="h-5 w-5 text-yellow-600" />
              <h3 className="font-medium text-yellow-900 dark:text-yellow-200">CAPTCHA Verification Required</h3>
            </div>
            <p className="text-sm text-yellow-800 dark:text-yellow-300 mb-4">
              Signal requires CAPTCHA verification to register this number. Follow these steps:
            </p>
            <ol className="text-sm text-yellow-800 dark:text-yellow-300 mb-4 list-decimal list-inside space-y-2">
              <li>
                <a
                  href={captchaUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-blue-600 dark:text-blue-400 hover:underline inline-flex items-center gap-1"
                >
                  Open the CAPTCHA page <ExternalLink className="h-3 w-3" />
                </a>
              </li>
              <li>Solve the CAPTCHA puzzle</li>
              <li>When the "Open Signal" button appears, <strong>right-click</strong> it</li>
              <li>Select "Copy link address" or "Copy Link"</li>
              <li>Paste the full link below (starts with <code className="bg-yellow-200 dark:bg-yellow-800 px-1 rounded">signalcaptcha://</code>)</li>
            </ol>
            <div className="space-y-3">
              <input
                type="text"
                value={captchaToken}
                onChange={(e) => setCaptchaToken(e.target.value)}
                placeholder="signalcaptcha://signal-hcaptcha..."
                className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary font-mono text-sm"
              />
              <div className="flex gap-3">
                <button
                  onClick={handleSubmitCaptcha}
                  disabled={isLoading || !captchaToken}
                  className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50"
                >
                  {isLoading ? (
                    <>
                      <Loader2 className="h-4 w-4 mr-2 inline animate-spin" />
                      Verifying...
                    </>
                  ) : (
                    'Submit CAPTCHA & Continue'
                  )}
                </button>
                <button
                  onClick={() => {
                    setShowCaptcha(false);
                    setCaptchaToken('');
                    setShowRegister(false);
                    setRegisterPhone('');
                  }}
                  className="px-4 py-2 border border-input text-foreground rounded-md hover:bg-accent"
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Verify Code */}
        {showVerify && (
          <div className="mb-6 p-4 border border-border rounded-lg">
            <h3 className="font-medium text-foreground mb-3">Enter Verification Code</h3>
            <p className="text-sm text-muted-foreground mb-3">
              A verification code was sent to {registerPhone}
            </p>
            <div className="flex gap-3">
              <input
                type="text"
                value={verifyCode}
                onChange={(e) => setVerifyCode(e.target.value)}
                placeholder="123456"
                className="flex-1 px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              />
              <button
                onClick={handleVerifyNumber}
                disabled={isLoading || !verifyCode}
                className="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 disabled:opacity-50"
              >
                {isLoading ? 'Verifying...' : 'Verify'}
              </button>
              <button
                onClick={() => {
                  setShowVerify(false);
                  setVerifyCode('');
                }}
                className="px-4 py-2 border border-input text-foreground rounded-md hover:bg-accent"
              >
                Cancel
              </button>
            </div>
          </div>
        )}

        {/* Test Message (when linked) */}
        {signalStatus?.isLinked && (
          <div className="p-4 border border-border rounded-lg">
            <h3 className="font-medium text-foreground mb-3">Send Test Message</h3>
            <div className="space-y-3">
              <input
                type="tel"
                value={testRecipient}
                onChange={(e) => setTestRecipient(e.target.value)}
                placeholder="Recipient phone number (+1234567890)"
                className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              />
              <textarea
                value={testMessage}
                onChange={(e) => setTestMessage(e.target.value)}
                placeholder="Test message..."
                rows={2}
                className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
              />
              <button
                onClick={handleSendTestMessage}
                disabled={isLoading || !testRecipient || !testMessage}
                className="inline-flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 transition-colors"
              >
                <Send className="h-4 w-4 mr-2" />
                {isLoading ? 'Sending...' : 'Send Test Message'}
              </button>
            </div>
          </div>
        )}

        {/* Chat Management (when linked) */}
        {signalStatus?.isLinked && (
          <div className="mt-6 p-4 border border-border rounded-lg">
            <h3 className="font-medium text-foreground mb-3">Chat History Management</h3>

            {/* Stats */}
            {messageStats && (
              <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-4 p-3 bg-muted/30 rounded-lg">
                <div className="text-center">
                  <div className="text-xl font-bold text-foreground">{messageStats.total}</div>
                  <div className="text-xs text-muted-foreground">Total Messages</div>
                </div>
                <div className="text-center">
                  <div className="text-xl font-bold text-blue-600">{messageStats.inbound}</div>
                  <div className="text-xs text-muted-foreground">Received</div>
                </div>
                <div className="text-center">
                  <div className="text-xl font-bold text-green-600">{messageStats.outbound}</div>
                  <div className="text-xs text-muted-foreground">Sent</div>
                </div>
                <div className="text-center">
                  <div className="text-xl font-bold text-orange-600">{messageStats.unread}</div>
                  <div className="text-xs text-muted-foreground">Unread</div>
                </div>
                <div className="text-center">
                  <div className="text-xl font-bold text-purple-600">{messageStats.driversWithMessages}</div>
                  <div className="text-xs text-muted-foreground">Drivers</div>
                </div>
              </div>
            )}

            <div className="flex gap-3">
              <button
                onClick={handleExportChats}
                disabled={isLoading || !messageStats?.total}
                className="inline-flex items-center px-4 py-2 border border-input text-foreground rounded-md hover:bg-accent disabled:opacity-50 transition-colors"
              >
                <Download className="h-4 w-4 mr-2" />
                Export Chats
              </button>
              <button
                onClick={handleDeleteAllChats}
                disabled={isLoading || !messageStats?.total}
                className="inline-flex items-center px-4 py-2 border border-red-300 dark:border-red-700 text-red-700 dark:text-red-400 rounded-md hover:bg-red-50 dark:hover:bg-red-950/20 disabled:opacity-50 transition-colors"
              >
                <Trash2 className="h-4 w-4 mr-2" />
                Delete All Chats
              </button>
              <button
                onClick={() => refetchMessageStats()}
                className="inline-flex items-center px-3 py-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
              >
                <RefreshCw className="h-4 w-4" />
              </button>
            </div>
          </div>
        )}

        {/* Not Connected Message */}
        {!signalStatus?.isConnected && !signalLoading && (
          <div className="p-4 border border-yellow-300 dark:border-yellow-700 bg-yellow-50 dark:bg-yellow-950/20 rounded-lg">
            <p className="text-yellow-800 dark:text-yellow-200">
              <AlertTriangle className="h-4 w-4 inline mr-2" />
              Signal API is not running. Start the signal-api container:
            </p>
            <code className="block mt-2 p-2 bg-background rounded text-sm">
              docker-compose up -d signal-api
            </code>
          </div>
        )}
      </div>

      {/* Test Data & Clear Operations */}
      <div className="bg-card border border-border shadow-soft rounded-lg p-6 transition-colors">
        <div className="flex items-center mb-4">
          <AlertTriangle className="h-5 w-5 text-orange-600 mr-2" />
          <h2 className="text-lg font-medium text-foreground">Test Data Management</h2>
        </div>
        <p className="text-muted-foreground mb-6">
          Generate realistic test data for development and demos. All operations use fast bulk database queries.
        </p>

        <div className="space-y-4">
          {/* Quick Actions */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Generate All Data */}
            <div className="p-4 border-2 border-green-300 dark:border-green-700 bg-green-50 dark:bg-green-950/20 rounded-lg transition-colors">
              <h3 className="font-medium text-green-900 dark:text-green-200 mb-2">Generate Complete Test Data</h3>
              <p className="text-sm text-green-700 dark:text-green-300 mb-3">
                Creates 20 VIPs, 8 drivers, 10 vehicles, flights, and 100+ events with times relative to NOW.
                Includes in-progress events, urgent pickups, and completed activities.
              </p>
              <button
                onClick={handleGenerateAllData}
                disabled={isLoading}
                className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 disabled:opacity-50 transition-colors w-full justify-center"
              >
                {isLoading ? (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                ) : (
                  <Plus className="h-4 w-4 mr-2" />
                )}
                Generate All Data (Fast!)
              </button>
            </div>

            {/* Regenerate Events Only */}
            <div className="p-4 border-2 border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-950/20 rounded-lg transition-colors">
              <h3 className="font-medium text-blue-900 dark:text-blue-200 mb-2">Refresh Event Times</h3>
              <p className="text-sm text-blue-700 dark:text-blue-300 mb-3">
                Keeps existing VIPs, drivers, and vehicles but regenerates all events with fresh times
                relative to NOW. Great for testing the Command Center.
              </p>
              <button
                onClick={handleRegenerateEvents}
                disabled={isLoading}
                className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 transition-colors w-full justify-center"
              >
                {isLoading ? (
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                ) : (
                  <RefreshCw className="h-4 w-4 mr-2" />
                )}
                Regenerate Events (Fast!)
              </button>
            </div>
          </div>

          {/* Info box about generated data */}
          <div className="p-3 bg-muted/30 border border-border rounded-lg text-sm text-muted-foreground">
            <strong className="text-foreground">Generated events include:</strong>
            <ul className="mt-1 ml-4 list-disc space-y-0.5">
              <li><span className="text-yellow-600 dark:text-yellow-400 font-medium">IN_PROGRESS</span> - Active pickups and meetings happening now</li>
              <li><span className="text-red-600 dark:text-red-400 font-medium">URGENT</span> - Events starting in 5-15 minutes</li>
              <li><span className="text-blue-600 dark:text-blue-400 font-medium">SCHEDULED</span> - Upcoming events throughout the day</li>
              <li><span className="text-green-600 dark:text-green-400 font-medium">COMPLETED</span> - Recently finished events</li>
              <li><span className="text-purple-600 dark:text-purple-400 font-medium">Multi-VIP</span> - Group transport events</li>
            </ul>
          </div>

          {/* Danger Zone */}
          <div className="flex items-center justify-between p-4 border-2 border-red-400 dark:border-red-700 bg-red-50 dark:bg-red-950/20 rounded-lg transition-colors">
            <div>
              <h3 className="font-medium text-red-900 dark:text-red-200">Clear All Data</h3>
              <p className="text-sm text-red-700 dark:text-red-300">Instantly delete all VIPs, drivers, vehicles, events, flights, and messages</p>
            </div>
            <button
              onClick={handleClearAllData}
              disabled={isLoading}
              className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 disabled:opacity-50 transition-colors"
            >
              {isLoading ? (
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
              ) : (
                <Trash2 className="h-4 w-4 mr-2" />
              )}
              Clear All Data
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
