/**
 * Communication Settings Page
 *
 * Manage SMS and calling credits, auto-reload settings, and view transaction history.
 */

import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useOutletContext } from 'react-router-dom';
import {
  Phone, Wallet, RefreshCw, Check, CreditCard, Loader2,
  ArrowUpRight, ArrowDownRight, ArrowRight, Clock, Save, MessageSquare,
  PhoneCall, Trash2, RefreshCcw, Search, Plus, AlertCircle, X, CheckCircle
} from 'lucide-react';
import { Business, User } from '../../types';
import {
  useCommunicationCredits,
  useCreditTransactions,
  useUpdateCreditsSettings,
  usePhoneNumbers,
  useSearchPhoneNumbers,
  usePurchasePhoneNumber,
  useReleasePhoneNumber,
  useChangePhoneNumber,
  ProxyPhoneNumber,
  AvailablePhoneNumber,
} from '../../hooks/useCommunicationCredits';
import { CreditPaymentModal } from '../../components/CreditPaymentForm';
import { usePlanFeatures } from '../../hooks/usePlanFeatures';
import { LockedSection } from '../../components/UpgradePrompt';

const CommunicationSettings: React.FC = () => {
  const { t } = useTranslation();
  const { business, user } = useOutletContext<{
    business: Business;
    user: User;
  }>();

  const { data: credits, isLoading: creditsLoading } = useCommunicationCredits();
  const { data: transactions } = useCreditTransactions(1, 10);
  const updateSettings = useUpdateCreditsSettings();

  // Phone number hooks
  const { data: phoneNumbers, isLoading: phoneNumbersLoading } = usePhoneNumbers();
  const searchPhoneNumbers = useSearchPhoneNumbers();
  const purchasePhoneNumber = usePurchasePhoneNumber();
  const releasePhoneNumber = useReleasePhoneNumber();
  const changePhoneNumber = useChangePhoneNumber();

  // Wizard state
  const [showWizard, setShowWizard] = useState(false);
  const [wizardStep, setWizardStep] = useState(1);
  const [wizardData, setWizardData] = useState({
    appointmentsPerMonth: 100,
    smsRemindersEnabled: true,
    smsPerAppointment: 2,
    maskedCallingEnabled: false,
    avgCallMinutes: 3,
    callsPerMonth: 20,
    callingPattern: 'sequential' as 'concurrent' | 'sequential',
    staffCount: 1,
    maxDailyAppointmentsPerStaff: 8,
  });

  // Settings form state
  const [settingsForm, setSettingsForm] = useState({
    auto_reload_enabled: credits?.auto_reload_enabled ?? false,
    auto_reload_threshold_cents: credits?.auto_reload_threshold_cents ?? 1000,
    auto_reload_amount_cents: credits?.auto_reload_amount_cents ?? 2500,
    low_balance_warning_cents: credits?.low_balance_warning_cents ?? 500,
  });

  // Top-up modal state
  const [showTopUp, setShowTopUp] = useState(false);
  const [topUpAmount, setTopUpAmount] = useState(2500);
  const [skipAmountSelection, setSkipAmountSelection] = useState(false);

  // Phone number management state
  const [showPhoneSearch, setShowPhoneSearch] = useState(false);
  const [phoneSearchQuery, setPhoneSearchQuery] = useState({ area_code: '', contains: '' });
  const [availableNumbers, setAvailableNumbers] = useState<AvailablePhoneNumber[]>([]);
  const [selectedNumber, setSelectedNumber] = useState<AvailablePhoneNumber | null>(null);
  const [numberToRelease, setNumberToRelease] = useState<ProxyPhoneNumber | null>(null);
  const [numberToChange, setNumberToChange] = useState<ProxyPhoneNumber | null>(null);
  const [phoneError, setPhoneError] = useState<string | null>(null);

  // Wizard phone number selection state (single number only)
  const [showWizardPhoneModal, setShowWizardPhoneModal] = useState(false);
  const [wizardSelectedNumber, setWizardSelectedNumber] = useState<AvailablePhoneNumber | null>(null);
  const [wizardPhoneSearchQuery, setWizardPhoneSearchQuery] = useState({ area_code: '', contains: '' });
  const [wizardAvailableNumbers, setWizardAvailableNumbers] = useState<AvailablePhoneNumber[]>([]);

  const isOwner = user.role === 'owner';
  const { canUse } = usePlanFeatures();

  // Update settings form when credits data loads
  useEffect(() => {
    if (credits) {
      setSettingsForm({
        auto_reload_enabled: credits.auto_reload_enabled,
        auto_reload_threshold_cents: credits.auto_reload_threshold_cents,
        auto_reload_amount_cents: credits.auto_reload_amount_cents,
        low_balance_warning_cents: credits.low_balance_warning_cents,
      });
    }
  }, [credits]);

  // Check if needs setup
  const needsSetup = !credits || (credits.balance_cents === 0 && credits.total_loaded_cents === 0);

  // Check if phone number is needed (single number for all SMS and calling)
  const needsPhoneNumber = () => {
    return wizardData.smsRemindersEnabled || wizardData.maskedCallingEnabled;
  };

  // Calculate estimated monthly cost
  const calculateEstimate = () => {
    let totalCents = 0;
    if (wizardData.smsRemindersEnabled) {
      const smsCount = wizardData.appointmentsPerMonth * wizardData.smsPerAppointment;
      totalCents += smsCount * 3;
    }
    if (wizardData.maskedCallingEnabled) {
      const callMinutes = wizardData.callsPerMonth * wizardData.avgCallMinutes;
      totalCents += callMinutes * 5;
    }
    // Single phone number for both SMS and calling ($2/month)
    if (needsPhoneNumber()) {
      totalCents += 200;
    }
    return totalCents;
  };

  // Calculate recommended starting balance
  const getRecommendedBalance = () => {
    const monthlyEstimate = calculateEstimate();
    return Math.max(2500, Math.ceil((monthlyEstimate * 2.5) / 500) * 500);
  };

  const handleSaveSettings = async () => {
    await updateSettings.mutateAsync(settingsForm);
  };

  const handlePaymentSuccess = async () => {
    if (showWizard || needsSetup) {
      await updateSettings.mutateAsync(settingsForm);
    }
    setShowTopUp(false);
    setShowWizard(false);
  };

  const formatCurrency = (cents: number) => {
    return `$${(cents / 100).toFixed(2)}`;
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const formatPhoneNumber = (phone: string) => {
    const cleaned = phone.replace(/\D/g, '');
    if (cleaned.length === 11 && cleaned.startsWith('1')) {
      return `+1 (${cleaned.slice(1, 4)}) ${cleaned.slice(4, 7)}-${cleaned.slice(7)}`;
    }
    return phone;
  };

  const handleSearchPhoneNumbers = async () => {
    setPhoneError(null);
    try {
      const result = await searchPhoneNumbers.mutateAsync(phoneSearchQuery);
      setAvailableNumbers(result.numbers);
    } catch (err: any) {
      setPhoneError(err.response?.data?.error || 'Failed to search phone numbers');
    }
  };

  const handlePurchaseNumber = async (number: AvailablePhoneNumber) => {
    setPhoneError(null);
    try {
      await purchasePhoneNumber.mutateAsync({
        phone_number: number.phone_number,
        friendly_name: number.friendly_name,
      });
      setShowPhoneSearch(false);
      setAvailableNumbers([]);
      setSelectedNumber(null);
    } catch (err: any) {
      setPhoneError(err.response?.data?.error || 'Failed to purchase phone number');
    }
  };

  const handleReleaseNumber = async () => {
    if (!numberToRelease) return;
    setPhoneError(null);
    try {
      await releasePhoneNumber.mutateAsync(numberToRelease.id);
      setNumberToRelease(null);
    } catch (err: any) {
      setPhoneError(err.response?.data?.error || 'Failed to release phone number');
    }
  };

  const handleChangeNumber = async (newNumber: AvailablePhoneNumber) => {
    if (!numberToChange) return;
    setPhoneError(null);
    try {
      await changePhoneNumber.mutateAsync({
        numberId: numberToChange.id,
        new_phone_number: newNumber.phone_number,
        friendly_name: newNumber.friendly_name,
      });
      setNumberToChange(null);
      setAvailableNumbers([]);
    } catch (err: any) {
      setPhoneError(err.response?.data?.error || 'Failed to change phone number');
    }
  };

  // Wizard phone number selection handlers
  const handleWizardPhoneSearch = async () => {
    setPhoneError(null);
    try {
      const result = await searchPhoneNumbers.mutateAsync(wizardPhoneSearchQuery);
      setWizardAvailableNumbers(result.numbers);
    } catch (err: any) {
      setPhoneError(err.response?.data?.error || 'Failed to search phone numbers');
    }
  };

  const handleWizardSelectNumber = (number: AvailablePhoneNumber) => {
    // Single number selection - toggle on/off
    if (wizardSelectedNumber?.phone_number === number.phone_number) {
      setWizardSelectedNumber(null);
    } else {
      setWizardSelectedNumber(number);
    }
  };

  const handleWizardPhoneConfirm = () => {
    // Close modal and advance to step 4
    setShowWizardPhoneModal(false);
    setWizardStep(4);
  };

  if (!isOwner) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-500 dark:text-gray-400">
          Only the business owner can access these settings.
        </p>
      </div>
    );
  }

  if (creditsLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-brand-600" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
            <Phone className="text-green-500" />
            SMS & Calling Credits
          </h2>
          <p className="text-gray-500 dark:text-gray-400 mt-1">
            Manage your prepaid credits for SMS reminders and masked calling.
          </p>
        </div>
        {!needsSetup && (
          <button
            onClick={() => setShowWizard(true)}
            className="text-sm text-brand-600 hover:text-brand-700 dark:text-brand-400"
          >
            Recalculate usage
          </button>
        )}
      </div>

      <LockedSection feature="sms_reminders" isLocked={!canUse('sms_reminders')}>

      {/* Setup Wizard or Main Content */}
      {needsSetup || showWizard ? (
        <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
          <div className="mb-6">
            <h4 className="text-lg font-medium text-gray-900 dark:text-white">
              {needsSetup ? 'Set Up Communication Credits' : 'Estimate Your Usage'}
            </h4>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              Answer a few questions to estimate your monthly communication costs
            </p>
          </div>

          {/* Progress Steps */}
          <div className="flex items-center gap-2 mb-8">
            {[1, 2, 3, 4].map((step) => (
              <React.Fragment key={step}>
                <div
                  className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
                    wizardStep >= step
                      ? 'bg-brand-600 text-white'
                      : 'bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400'
                  }`}
                >
                  {wizardStep > step ? <Check className="w-4 h-4" /> : step}
                </div>
                {step < 4 && (
                  <div
                    className={`flex-1 h-1 ${
                      wizardStep > step ? 'bg-brand-600' : 'bg-gray-200 dark:bg-gray-700'
                    }`}
                  />
                )}
              </React.Fragment>
            ))}
          </div>

          {/* Step 1: Appointment Volume */}
          {wizardStep === 1 && (
            <div className="space-y-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  How many appointments do you handle per month?
                </label>
                <input
                  type="number"
                  min="0"
                  value={wizardData.appointmentsPerMonth}
                  onChange={(e) =>
                    setWizardData({ ...wizardData, appointmentsPerMonth: parseInt(e.target.value) || 0 })
                  }
                  className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-lg"
                  placeholder="100"
                />
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
                  Include all appointments: new bookings, rescheduled, and recurring
                </p>
              </div>
              <div className="flex justify-end">
                <button
                  onClick={() => setWizardStep(2)}
                  className="px-6 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700"
                >
                  Continue
                </button>
              </div>
            </div>
          )}

          {/* Step 2: SMS Settings */}
          {wizardStep === 2 && (
            <div className="space-y-6">
              <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                <label className="flex items-center justify-between">
                  <div>
                    <span className="text-sm font-medium text-gray-900 dark:text-white">
                      Enable SMS Reminders
                    </span>
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Send text reminders to customers and staff
                    </p>
                  </div>
                  <input
                    type="checkbox"
                    checked={wizardData.smsRemindersEnabled}
                    onChange={(e) =>
                      setWizardData({ ...wizardData, smsRemindersEnabled: e.target.checked })
                    }
                    className="rounded border-gray-300 text-brand-600 focus:ring-brand-500 w-5 h-5"
                  />
                </label>
              </div>

              {wizardData.smsRemindersEnabled && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    SMS messages per appointment
                  </label>
                  <select
                    value={wizardData.smsPerAppointment}
                    onChange={(e) =>
                      setWizardData({ ...wizardData, smsPerAppointment: parseInt(e.target.value) })
                    }
                    className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  >
                    <option value="1">1 - Reminder only</option>
                    <option value="2">2 - Confirmation + Reminder</option>
                    <option value="3">3 - Confirmation + Reminder + Follow-up</option>
                    <option value="4">4 - All of above + Staff notifications</option>
                  </select>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-2">
                    Cost: $0.03 per SMS message
                  </p>
                </div>
              )}

              <div className="flex justify-between">
                <button
                  onClick={() => setWizardStep(1)}
                  className="px-6 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
                >
                  Back
                </button>
                <button
                  onClick={() => setWizardStep(3)}
                  className="px-6 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700"
                >
                  Continue
                </button>
              </div>
            </div>
          )}

          {/* Step 3: Masked Calling */}
          {wizardStep === 3 && (
            <div className="space-y-6">
              <div className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                <label className="flex items-center justify-between">
                  <div>
                    <span className="text-sm font-medium text-gray-900 dark:text-white">
                      Enable Masked Calling
                    </span>
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Allow customers and staff to call each other without revealing real numbers
                    </p>
                  </div>
                  <input
                    type="checkbox"
                    checked={wizardData.maskedCallingEnabled}
                    onChange={(e) =>
                      setWizardData({ ...wizardData, maskedCallingEnabled: e.target.checked })
                    }
                    className="rounded border-gray-300 text-brand-600 focus:ring-brand-500 w-5 h-5"
                  />
                </label>
              </div>

              {wizardData.maskedCallingEnabled && (
                <>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Estimated calls per month
                      </label>
                      <input
                        type="number"
                        min="0"
                        value={wizardData.callsPerMonth}
                        onChange={(e) =>
                          setWizardData({ ...wizardData, callsPerMonth: parseInt(e.target.value) || 0 })
                        }
                        className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Average call duration (minutes)
                      </label>
                      <input
                        type="number"
                        min="1"
                        value={wizardData.avgCallMinutes}
                        onChange={(e) =>
                          setWizardData({ ...wizardData, avgCallMinutes: parseInt(e.target.value) || 1 })
                        }
                        className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                      />
                    </div>
                  </div>
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    Cost: $0.05 per minute of voice calling
                  </p>

                  {/* Phone Number Configuration for Masked Calling */}
                  <div className="mt-4 p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                    <div className="mb-3">
                      <span className="text-sm font-medium text-gray-900 dark:text-white">
                        Phone Numbers for Masked Calling
                      </span>
                      <p className="text-xs text-gray-500 dark:text-gray-400">
                        You'll need dedicated phone numbers for masked calling ($2/month each)
                      </p>
                    </div>

                    <div className="space-y-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                          How do your staff make calls?
                        </label>
                        <div className="space-y-2">
                          <label className="flex items-center gap-3 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
                            <input
                              type="radio"
                              name="callingPattern"
                              checked={wizardData.callingPattern === 'sequential'}
                              onChange={() => setWizardData({ ...wizardData, callingPattern: 'sequential' })}
                              className="text-brand-600 focus:ring-brand-500"
                            />
                            <div>
                              <span className="text-sm font-medium text-gray-900 dark:text-white">
                                One call at a time (sequential)
                              </span>
                              <p className="text-xs text-gray-500 dark:text-gray-400">
                                Staff finish one call before starting another
                              </p>
                            </div>
                          </label>
                          <label className="flex items-center gap-3 p-3 border border-gray-200 dark:border-gray-700 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50">
                            <input
                              type="radio"
                              name="callingPattern"
                              checked={wizardData.callingPattern === 'concurrent'}
                              onChange={() => setWizardData({ ...wizardData, callingPattern: 'concurrent' })}
                              className="text-brand-600 focus:ring-brand-500"
                            />
                            <div>
                              <span className="text-sm font-medium text-gray-900 dark:text-white">
                                Multiple calls at once (concurrent)
                              </span>
                              <p className="text-xs text-gray-500 dark:text-gray-400">
                                Multiple customers may call about the same appointment
                              </p>
                            </div>
                          </label>
                        </div>
                      </div>

                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Number of staff making calls
                          </label>
                          <input
                            type="number"
                            min="1"
                            value={wizardData.staffCount}
                            onChange={(e) =>
                              setWizardData({ ...wizardData, staffCount: parseInt(e.target.value) || 1 })
                            }
                            className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                          />
                        </div>
                        {wizardData.callingPattern === 'concurrent' && (
                          <div>
                            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                              Max concurrent calls
                            </label>
                            <input
                              type="number"
                              min="1"
                              value={wizardData.maxDailyAppointmentsPerStaff}
                              onChange={(e) =>
                                setWizardData({ ...wizardData, maxDailyAppointmentsPerStaff: parseInt(e.target.value) || 1 })
                              }
                              className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                            />
                          </div>
                        )}
                      </div>

                      {/* Phone Number Info */}
                      <div className="bg-brand-50 dark:bg-brand-900/20 rounded-lg p-4">
                        <div className="flex items-center gap-2 mb-2">
                          <PhoneCall className="w-5 h-5 text-brand-600" />
                          <span className="font-medium text-brand-900 dark:text-brand-100">
                            Phone Number Required
                          </span>
                        </div>
                        <p className="text-sm text-brand-800 dark:text-brand-200">
                          You'll need 1 phone number for all outbound calls.
                          {wizardData.smsRemindersEnabled && ' This number will also handle your SMS messages.'}
                        </p>
                        <p className="text-sm text-brand-700 dark:text-brand-300 mt-2">
                          Monthly cost: {formatCurrency(200)}
                        </p>
                      </div>
                    </div>
                  </div>
                </>
              )}

              {/* Phone Number Notice for SMS-only (when calling is not enabled) */}
              {wizardData.smsRemindersEnabled && !wizardData.maskedCallingEnabled && (
                <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4 border border-blue-200 dark:border-blue-800">
                  <div className="flex items-center gap-2 mb-2">
                    <MessageSquare className="w-5 h-5 text-blue-600" />
                    <span className="font-medium text-blue-900 dark:text-blue-100">
                      Phone Number Required for SMS
                    </span>
                  </div>
                  <p className="text-sm text-blue-800 dark:text-blue-200">
                    You'll need 1 phone number to send and receive SMS messages. Cost: $2/month.
                  </p>
                  <p className="text-xs text-blue-700 dark:text-blue-300 mt-2">
                    You can purchase a phone number after completing setup.
                  </p>
                </div>
              )}

              <div className="flex justify-between">
                <button
                  onClick={() => setWizardStep(2)}
                  className="px-6 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
                >
                  Back
                </button>
                {needsPhoneNumber() ? (
                  <button
                    onClick={() => setShowWizardPhoneModal(true)}
                    className="px-6 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 flex items-center gap-2"
                  >
                    <PhoneCall className="w-4 h-4" />
                    Choose Number
                  </button>
                ) : (
                  <button
                    onClick={() => setWizardStep(4)}
                    className="px-6 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700"
                  >
                    See Estimate
                  </button>
                )}
              </div>
            </div>
          )}

          {/* Step 4: Auto-Reload Setup */}
          {wizardStep === 4 && (
            <div className="space-y-6">
              {/* Monthly Estimate Summary */}
              <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                <div className="flex justify-between items-center">
                  <span className="text-sm text-gray-600 dark:text-gray-400">
                    Your estimated monthly usage
                  </span>
                  <span className="text-lg font-bold text-gray-900 dark:text-white">
                    {formatCurrency(calculateEstimate())}/month
                  </span>
                </div>
                <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  {wizardData.smsRemindersEnabled && (
                    <span>SMS: {wizardData.appointmentsPerMonth * wizardData.smsPerAppointment} messages</span>
                  )}
                  {wizardData.smsRemindersEnabled && wizardData.maskedCallingEnabled && <span> · </span>}
                  {wizardData.maskedCallingEnabled && (
                    <span>Calls: {wizardData.callsPerMonth * wizardData.avgCallMinutes} minutes</span>
                  )}
                </div>
              </div>

              {/* Auto-Reload Configuration */}
              <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-6">
                <h5 className="font-medium text-gray-900 dark:text-white mb-1">
                  Set Up Auto-Reload
                </h5>
                <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
                  We'll automatically keep your balance topped up so your services never get interrupted.
                </p>

                {/* Reload Amount Selection */}
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                    How much should we reload?
                  </label>
                  <div className="grid grid-cols-5 gap-3">
                    {[1000, 2500, 5000, 10000].map((amount) => (
                      <button
                        key={amount}
                        onClick={() => {
                          setTopUpAmount(amount);
                          setSettingsForm({
                            ...settingsForm,
                            auto_reload_enabled: true,
                            auto_reload_amount_cents: amount,
                          });
                        }}
                        className={`py-3 px-4 rounded-lg border-2 transition-colors ${
                          topUpAmount === amount
                            ? 'border-brand-600 bg-brand-50 dark:bg-brand-900/30 text-brand-600'
                            : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                        }`}
                      >
                        <span className="font-semibold">{formatCurrency(amount)}</span>
                      </button>
                    ))}
                    <div className="relative">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400 font-medium">$</span>
                      <input
                        type="number"
                        min="5"
                        step="1"
                        placeholder="Custom"
                        value={[1000, 2500, 5000, 10000].includes(topUpAmount) ? '' : topUpAmount / 100}
                        onChange={(e) => {
                          const val = Math.max(5, parseInt(e.target.value) || 5) * 100;
                          setTopUpAmount(val);
                          setSettingsForm({
                            ...settingsForm,
                            auto_reload_enabled: true,
                            auto_reload_amount_cents: val,
                          });
                        }}
                        className={`w-full py-3 pl-7 pr-3 rounded-lg border-2 transition-colors text-center font-semibold ${
                          ![1000, 2500, 5000, 10000].includes(topUpAmount)
                            ? 'border-brand-600 bg-brand-50 dark:bg-brand-900/30 text-brand-600'
                            : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white'
                        }`}
                      />
                    </div>
                  </div>
                </div>

                {/* Low Threshold Selection */}
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                    Reload when balance falls below
                  </label>
                  <div className="grid grid-cols-5 gap-3">
                    {[500, 1000, 2000, 5000].map((threshold) => (
                      <button
                        key={threshold}
                        onClick={() => {
                          setSettingsForm({
                            ...settingsForm,
                            auto_reload_threshold_cents: threshold,
                            low_balance_warning_cents: Math.round(threshold * 0.5),
                          });
                        }}
                        className={`py-3 px-4 rounded-lg border-2 transition-colors ${
                          settingsForm.auto_reload_threshold_cents === threshold
                            ? 'border-brand-600 bg-brand-50 dark:bg-brand-900/30 text-brand-600'
                            : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                        }`}
                      >
                        <span className="font-semibold">{formatCurrency(threshold)}</span>
                      </button>
                    ))}
                    <div className="relative">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400 font-medium">$</span>
                      <input
                        type="number"
                        min="1"
                        step="1"
                        placeholder="Custom"
                        value={[500, 1000, 2000, 5000].includes(settingsForm.auto_reload_threshold_cents) ? '' : settingsForm.auto_reload_threshold_cents / 100}
                        onChange={(e) => {
                          const val = Math.max(1, parseInt(e.target.value) || 1) * 100;
                          setSettingsForm({
                            ...settingsForm,
                            auto_reload_threshold_cents: val,
                            low_balance_warning_cents: Math.round(val * 0.5),
                          });
                        }}
                        className={`w-full py-3 pl-7 pr-3 rounded-lg border-2 transition-colors text-center font-semibold ${
                          ![500, 1000, 2000, 5000].includes(settingsForm.auto_reload_threshold_cents)
                            ? 'border-brand-600 bg-brand-50 dark:bg-brand-900/30 text-brand-600'
                            : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white'
                        }`}
                      />
                    </div>
                  </div>
                </div>

                {/* Summary */}
                <div className="bg-brand-50 dark:bg-brand-900/20 rounded-lg p-4">
                  <h6 className="font-medium text-brand-900 dark:text-brand-100 text-sm mb-3">
                    Summary
                  </h6>
                  <div className="space-y-2 text-sm text-brand-800 dark:text-brand-200">
                    <p>
                      <strong>Today:</strong> We'll charge <strong>{formatCurrency(topUpAmount)}</strong> to load your initial credits.
                    </p>
                    <p>
                      <strong>Auto-reload:</strong> When your balance drops below <strong>{formatCurrency(settingsForm.auto_reload_threshold_cents)}</strong>, we'll automatically charge <strong>{formatCurrency(topUpAmount)}</strong> again.
                    </p>
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="flex justify-between">
                <button
                  onClick={() => setWizardStep(3)}
                  className="px-6 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
                >
                  Back
                </button>
                <div className="flex gap-3">
                  {!needsSetup && (
                    <button
                      onClick={() => setShowWizard(false)}
                      className="px-6 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
                    >
                      Cancel
                    </button>
                  )}
                  <button
                    onClick={() => {
                      setSkipAmountSelection(true);
                      setShowTopUp(true);
                    }}
                    className="px-6 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 flex items-center gap-2"
                  >
                    <CreditCard className="w-4 h-4" />
                    Continue to Payment
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      ) : (
        <>
          {/* Current Balance Card */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-gray-500 dark:text-gray-400">Current Balance</span>
                <Wallet className="w-5 h-5 text-gray-400" />
              </div>
              <p className="text-3xl font-bold text-gray-900 dark:text-white">
                {formatCurrency(credits?.balance_cents || 0)}
              </p>
              <button
                onClick={() => setShowTopUp(true)}
                className="mt-3 w-full py-2 text-sm font-medium text-brand-600 border border-brand-600 rounded-lg hover:bg-brand-50 dark:hover:bg-brand-900/20"
              >
                Add Credits
              </button>
            </div>

            <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-gray-500 dark:text-gray-400">Total Loaded</span>
                <ArrowUpRight className="w-5 h-5 text-green-500" />
              </div>
              <p className="text-3xl font-bold text-green-600">
                {formatCurrency(credits?.total_loaded_cents || 0)}
              </p>
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">All time</p>
            </div>

            <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-gray-500 dark:text-gray-400">Total Spent</span>
                <ArrowDownRight className="w-5 h-5 text-red-500" />
              </div>
              <p className="text-3xl font-bold text-gray-900 dark:text-white">
                {formatCurrency(credits?.total_spent_cents || 0)}
              </p>
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">All time</p>
            </div>
          </div>

          {/* Phone Numbers Section - needed for both SMS and calling */}
          {(canUse('sms_reminders') || canUse('masked_calling')) && (
            <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
              <div className="flex items-center justify-between mb-4">
                <h4 className="text-sm font-medium text-gray-900 dark:text-white flex items-center gap-2">
                  <PhoneCall className="w-4 h-4" />
                  Your Phone Number
                </h4>
                {/* Only one phone number allowed - no add button once they have one */}
              </div>

              {phoneNumbersLoading ? (
                <div className="flex items-center justify-center py-6">
                  <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
                </div>
              ) : phoneNumbers?.numbers && phoneNumbers.numbers.length > 0 ? (
                <div className="space-y-3">
                  {phoneNumbers.numbers.map((num) => (
                    <div
                      key={num.id}
                      className="flex items-center justify-between p-4 border border-gray-200 dark:border-gray-700 rounded-lg"
                    >
                      <div className="flex items-center gap-4">
                        <div className="w-10 h-10 rounded-full bg-brand-100 dark:bg-brand-900/30 flex items-center justify-center">
                          <Phone className="w-5 h-5 text-brand-600" />
                        </div>
                        <div>
                          <p className="font-medium text-gray-900 dark:text-white">
                            {formatPhoneNumber(num.phone_number)}
                          </p>
                          {num.friendly_name && (
                            <p className="text-xs text-gray-500 dark:text-gray-400">
                              {num.friendly_name}
                            </p>
                          )}
                          <div className="flex gap-2 mt-1">
                            {num.capabilities.voice && (
                              <span className="text-xs bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 px-2 py-0.5 rounded">
                                Voice
                              </span>
                            )}
                            {num.capabilities.sms && (
                              <span className="text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 px-2 py-0.5 rounded">
                                SMS
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="text-sm text-gray-500 dark:text-gray-400">
                          {formatCurrency(num.monthly_fee_cents)}/mo
                        </span>
                        <button
                          onClick={() => {
                            setNumberToChange(num);
                            setShowPhoneSearch(true);
                          }}
                          className="p-2 text-gray-400 hover:text-brand-600 dark:hover:text-brand-400"
                          title="Change number ($2 fee)"
                        >
                          <RefreshCcw className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => setNumberToRelease(num)}
                          className="p-2 text-gray-400 hover:text-red-600 dark:hover:text-red-400"
                          title="Release number"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-6">
                  <Phone className="w-10 h-10 text-gray-300 dark:text-gray-600 mx-auto mb-3" />
                  <p className="text-sm text-gray-500 dark:text-gray-400 mb-3">
                    No phone numbers yet
                  </p>
                  <button
                    onClick={() => setShowPhoneSearch(true)}
                    className="text-sm text-brand-600 hover:text-brand-700 dark:text-brand-400"
                  >
                    Get your first phone number
                  </button>
                </div>
              )}
            </div>
          )}

          {/* Auto-Reload Settings */}
          <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
            <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-4 flex items-center gap-2">
              <RefreshCw className="w-4 h-4" />
              Auto-Reload Settings
            </h4>

            <div className="space-y-4">
              <label className="flex items-center justify-between p-3 border border-gray-200 dark:border-gray-700 rounded-lg">
                <div>
                  <span className="text-sm font-medium text-gray-900 dark:text-white">
                    Enable Auto-Reload
                  </span>
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    Automatically add credits when balance falls below threshold
                  </p>
                </div>
                <input
                  type="checkbox"
                  checked={settingsForm.auto_reload_enabled}
                  onChange={(e) =>
                    setSettingsForm({ ...settingsForm, auto_reload_enabled: e.target.checked })
                  }
                  className="rounded border-gray-300 text-brand-600 focus:ring-brand-500 w-5 h-5"
                />
              </label>

              {settingsForm.auto_reload_enabled && (
                <div className="grid grid-cols-2 gap-4 pl-4 border-l-2 border-brand-200 dark:border-brand-800">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Reload when balance below
                    </label>
                    <div className="relative">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
                      <input
                        type="number"
                        min="1"
                        step="1"
                        value={(settingsForm.auto_reload_threshold_cents / 100).toFixed(0)}
                        onChange={(e) =>
                          setSettingsForm({
                            ...settingsForm,
                            auto_reload_threshold_cents: (parseFloat(e.target.value) || 0) * 100,
                          })
                        }
                        className="w-full pl-8 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                      />
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                      Reload amount
                    </label>
                    <div className="relative">
                      <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
                      <input
                        type="number"
                        min="5"
                        step="5"
                        value={(settingsForm.auto_reload_amount_cents / 100).toFixed(0)}
                        onChange={(e) =>
                          setSettingsForm({
                            ...settingsForm,
                            auto_reload_amount_cents: (parseFloat(e.target.value) || 0) * 100,
                          })
                        }
                        className="w-full pl-8 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                      />
                    </div>
                  </div>
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Low balance warning at
                </label>
                <div className="relative w-1/2">
                  <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">$</span>
                  <input
                    type="number"
                    min="1"
                    step="1"
                    value={(settingsForm.low_balance_warning_cents / 100).toFixed(0)}
                    onChange={(e) =>
                      setSettingsForm({
                        ...settingsForm,
                        low_balance_warning_cents: (parseFloat(e.target.value) || 0) * 100,
                      })
                    }
                    className="w-full pl-8 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
                <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  You'll receive an email when your balance drops below this amount
                </p>
              </div>

              <div className="pt-4">
                <button
                  onClick={handleSaveSettings}
                  disabled={updateSettings.isPending}
                  className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 flex items-center gap-2"
                >
                  {updateSettings.isPending ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Save className="w-4 h-4" />
                  )}
                  Save Settings
                </button>
              </div>
            </div>
          </div>

          {/* Transaction History */}
          <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-6">
            <h4 className="text-sm font-medium text-gray-900 dark:text-white mb-4 flex items-center gap-2">
              <Clock className="w-4 h-4" />
              Recent Transactions
            </h4>

            {transactions?.results && transactions.results.length > 0 ? (
              <div className="space-y-3">
                {transactions.results.map((tx: any) => (
                  <div
                    key={tx.id}
                    className="flex items-center justify-between py-3 border-b border-gray-100 dark:border-gray-700 last:border-0"
                  >
                    <div className="flex items-center gap-3">
                      <div
                        className={`w-8 h-8 rounded-full flex items-center justify-center ${
                          tx.amount_cents > 0
                            ? 'bg-green-100 dark:bg-green-900/30 text-green-600'
                            : 'bg-red-100 dark:bg-red-900/30 text-red-600'
                        }`}
                      >
                        {tx.amount_cents > 0 ? (
                          <ArrowUpRight className="w-4 h-4" />
                        ) : (
                          <ArrowDownRight className="w-4 h-4" />
                        )}
                      </div>
                      <div>
                        <p className="text-sm font-medium text-gray-900 dark:text-white">
                          {tx.description || tx.transaction_type.replace('_', ' ')}
                        </p>
                        <p className="text-xs text-gray-500 dark:text-gray-400">
                          {formatDate(tx.created_at)}
                        </p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p
                        className={`font-medium ${
                          tx.amount_cents > 0 ? 'text-green-600' : 'text-red-600'
                        }`}
                      >
                        {tx.amount_cents > 0 ? '+' : ''}
                        {formatCurrency(tx.amount_cents)}
                      </p>
                      <p className="text-xs text-gray-500 dark:text-gray-400">
                        Balance: {formatCurrency(tx.balance_after_cents)}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-sm text-gray-500 dark:text-gray-400 text-center py-4">
                No transactions yet
              </p>
            )}
          </div>
        </>
      )}

      {/* Credit Payment Modal */}
      <CreditPaymentModal
        isOpen={showTopUp}
        onClose={() => {
          setShowTopUp(false);
          setSkipAmountSelection(false);
        }}
        amountCents={topUpAmount}
        onAmountChange={setTopUpAmount}
        onSuccess={handlePaymentSuccess}
        skipAmountSelection={skipAmountSelection}
      />

      {/* Phone Number Search Modal */}
      {showPhoneSearch && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden">
            <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                  {numberToChange ? 'Change Phone Number' : 'Add Phone Number'}
                </h3>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  {numberToChange
                    ? `Select a new number to replace ${formatPhoneNumber(numberToChange.phone_number)} ($2 fee)`
                    : 'Search for available phone numbers ($2 purchase fee)'}
                </p>
              </div>
              <button
                onClick={() => {
                  setShowPhoneSearch(false);
                  setAvailableNumbers([]);
                  setPhoneSearchQuery({ area_code: '', contains: '' });
                  setNumberToChange(null);
                  setPhoneError(null);
                }}
                className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-6 overflow-y-auto max-h-[calc(90vh-180px)]">
              {/* Search Form */}
              <div className="flex gap-4 mb-6">
                <div className="flex-1">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Area Code
                  </label>
                  <input
                    type="text"
                    placeholder="e.g., 415"
                    maxLength={3}
                    value={phoneSearchQuery.area_code}
                    onChange={(e) =>
                      setPhoneSearchQuery({ ...phoneSearchQuery, area_code: e.target.value.replace(/\D/g, '') })
                    }
                    className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
                <div className="flex-1">
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Contains
                  </label>
                  <input
                    type="text"
                    placeholder="e.g., 1234"
                    maxLength={7}
                    value={phoneSearchQuery.contains}
                    onChange={(e) =>
                      setPhoneSearchQuery({ ...phoneSearchQuery, contains: e.target.value.replace(/\D/g, '') })
                    }
                    className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  />
                </div>
                <div className="flex items-end">
                  <button
                    onClick={handleSearchPhoneNumbers}
                    disabled={searchPhoneNumbers.isPending}
                    className="px-6 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 flex items-center gap-2"
                  >
                    {searchPhoneNumbers.isPending ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <Search className="w-4 h-4" />
                    )}
                    Search
                  </button>
                </div>
              </div>

              {phoneError && (
                <div className="flex items-start gap-2 p-3 mb-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg">
                  <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 shrink-0 mt-0.5" />
                  <p className="text-sm text-red-600 dark:text-red-400">{phoneError}</p>
                </div>
              )}

              {/* Available Numbers List */}
              {availableNumbers.length > 0 ? (
                <div className="space-y-2">
                  {availableNumbers.map((num) => (
                    <div
                      key={num.phone_number}
                      className="flex items-center justify-between p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50"
                    >
                      <div>
                        <p className="font-medium text-gray-900 dark:text-white">
                          {formatPhoneNumber(num.phone_number)}
                        </p>
                        <p className="text-sm text-gray-500 dark:text-gray-400">
                          {num.locality}, {num.region}
                        </p>
                        <div className="flex gap-2 mt-1">
                          {num.capabilities.voice && (
                            <span className="text-xs bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 px-2 py-0.5 rounded">
                              Voice
                            </span>
                          )}
                          {num.capabilities.sms && (
                            <span className="text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 px-2 py-0.5 rounded">
                              SMS
                            </span>
                          )}
                        </div>
                      </div>
                      <button
                        onClick={() =>
                          numberToChange
                            ? handleChangeNumber(num)
                            : handlePurchaseNumber(num)
                        }
                        disabled={purchasePhoneNumber.isPending || changePhoneNumber.isPending}
                        className="px-4 py-2 bg-brand-600 text-white text-sm rounded-lg hover:bg-brand-700 disabled:opacity-50 flex items-center gap-2"
                      >
                        {(purchasePhoneNumber.isPending || changePhoneNumber.isPending) ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <Plus className="w-4 h-4" />
                        )}
                        {numberToChange ? 'Select' : 'Purchase'} ($2.00)
                      </button>
                    </div>
                  ))}
                </div>
              ) : searchPhoneNumbers.isPending ? (
                <div className="text-center py-8">
                  <Loader2 className="w-8 h-8 animate-spin text-brand-600 mx-auto mb-3" />
                  <p className="text-gray-500 dark:text-gray-400">Searching for available numbers...</p>
                </div>
              ) : (
                <div className="text-center py-8">
                  <Search className="w-10 h-10 text-gray-300 dark:text-gray-600 mx-auto mb-3" />
                  <p className="text-gray-500 dark:text-gray-400">
                    Enter an area code and click Search to find available numbers
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Release Number Confirmation Modal */}
      {numberToRelease && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md p-6">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
              Release Phone Number?
            </h3>
            <p className="text-gray-600 dark:text-gray-400 mb-4">
              Are you sure you want to release {formatPhoneNumber(numberToRelease.phone_number)}?
              This will permanently remove the number from your account.
            </p>

            {phoneError && (
              <div className="flex items-start gap-2 p-3 mb-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg">
                <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 shrink-0 mt-0.5" />
                <p className="text-sm text-red-600 dark:text-red-400">{phoneError}</p>
              </div>
            )}

            <div className="flex gap-3">
              <button
                onClick={() => {
                  setNumberToRelease(null);
                  setPhoneError(null);
                }}
                className="flex-1 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
              >
                Cancel
              </button>
              <button
                onClick={handleReleaseNumber}
                disabled={releasePhoneNumber.isPending}
                className="flex-1 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {releasePhoneNumber.isPending ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Trash2 className="w-4 h-4" />
                )}
                Release Number
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Wizard Phone Number Selection Modal */}
      {showWizardPhoneModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
            <div className="p-6 border-b border-gray-200 dark:border-gray-700">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                    Choose Your Phone Number
                  </h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    Select a phone number for SMS and calling
                  </p>
                </div>
                <button
                  onClick={() => setShowWizardPhoneModal(false)}
                  className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              {/* Selected number indicator */}
              {wizardSelectedNumber && (
                <div className="mt-4 flex items-center gap-2">
                  <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    Selected:
                  </span>
                  <span className="inline-flex items-center gap-1 px-2 py-1 bg-brand-100 dark:bg-brand-900/30 text-brand-700 dark:text-brand-300 rounded-full text-sm">
                    {formatPhoneNumber(wizardSelectedNumber.phone_number)}
                    <button
                      onClick={() => setWizardSelectedNumber(null)}
                      className="hover:text-brand-900 dark:hover:text-brand-100"
                    >
                      <X className="w-3 h-3" />
                    </button>
                  </span>
                </div>
              )}

              {/* Search controls */}
              <div className="mt-4 flex gap-3">
                <div className="flex-1">
                  <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Area Code
                  </label>
                  <input
                    type="text"
                    placeholder="e.g., 415"
                    maxLength={3}
                    value={wizardPhoneSearchQuery.area_code}
                    onChange={(e) =>
                      setWizardPhoneSearchQuery({ ...wizardPhoneSearchQuery, area_code: e.target.value.replace(/\D/g, '') })
                    }
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                </div>
                <div className="flex-1">
                  <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Contains (optional)
                  </label>
                  <input
                    type="text"
                    placeholder="e.g., 1234"
                    maxLength={7}
                    value={wizardPhoneSearchQuery.contains}
                    onChange={(e) =>
                      setWizardPhoneSearchQuery({ ...wizardPhoneSearchQuery, contains: e.target.value.replace(/\D/g, '') })
                    }
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm"
                  />
                </div>
                <div className="flex items-end">
                  <button
                    onClick={handleWizardPhoneSearch}
                    disabled={searchPhoneNumbers.isPending}
                    className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 flex items-center gap-2"
                  >
                    {searchPhoneNumbers.isPending ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <Search className="w-4 h-4" />
                    )}
                    Search
                  </button>
                </div>
              </div>
            </div>

            {/* Search results */}
            <div className="flex-1 overflow-y-auto p-6">
              {phoneError && (
                <div className="flex items-start gap-2 p-3 mb-4 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg">
                  <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 shrink-0 mt-0.5" />
                  <p className="text-sm text-red-600 dark:text-red-400">{phoneError}</p>
                </div>
              )}

              {wizardAvailableNumbers.length > 0 ? (
                <div className="space-y-2">
                  {wizardAvailableNumbers.map((num) => {
                    const isSelected = wizardSelectedNumber?.phone_number === num.phone_number;
                    return (
                      <div
                        key={num.phone_number}
                        className={`flex items-center justify-between p-3 border rounded-lg transition-colors ${
                          isSelected
                            ? 'border-brand-500 bg-brand-50 dark:bg-brand-900/20'
                            : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                        }`}
                      >
                        <div>
                          <p className="font-medium text-gray-900 dark:text-white">
                            {formatPhoneNumber(num.phone_number)}
                          </p>
                          <p className="text-sm text-gray-500 dark:text-gray-400">
                            {num.locality}, {num.region}
                          </p>
                        </div>
                        <div className="flex items-center gap-3">
                          <span className="text-sm text-gray-600 dark:text-gray-400">
                            $2.00/mo
                          </span>
                          <button
                            onClick={() => handleWizardSelectNumber(num)}
                            className={`px-4 py-2 text-sm rounded-lg flex items-center gap-2 ${
                              isSelected
                                ? 'bg-brand-600 text-white hover:bg-brand-700'
                                : 'border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                            }`}
                          >
                            {isSelected ? (
                              <>
                                <CheckCircle className="w-4 h-4" />
                                Selected
                              </>
                            ) : (
                              <>
                                <Plus className="w-4 h-4" />
                                Select
                              </>
                            )}
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              ) : searchPhoneNumbers.isPending ? (
                <div className="text-center py-8">
                  <Loader2 className="w-8 h-8 animate-spin text-brand-600 mx-auto mb-3" />
                  <p className="text-gray-500 dark:text-gray-400">Searching for available numbers...</p>
                </div>
              ) : (
                <div className="text-center py-8">
                  <PhoneCall className="w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-3" />
                  <p className="text-gray-500 dark:text-gray-400">
                    Enter an area code and click Search to find available numbers
                  </p>
                </div>
              )}
            </div>

            {/* Footer with action buttons */}
            {/* TODO: Phone number availability is limited. Future implementation will need a phone app
                to handle cases where we can't provision enough Twilio numbers for all staff.
                Consider: SIP trunking, shared number pools, or mobile app with VoIP integration.

                TODO: Premium Dedicated Number Service
                - Allow businesses to request their own dedicated caller ID/number (not from pool)
                - Premium service: purchase number from another carrier and port to Twilio
                - Requires support ticket submission (manual process with human interaction)
                - Higher monthly fee for dedicated numbers
                - Add FAQ entry explaining this premium option and how to request it */}
            <div className="p-6 border-t border-gray-200 dark:border-gray-700">
              <div className="flex items-center justify-between">
                <div className="text-sm text-gray-500 dark:text-gray-400">
                  {wizardSelectedNumber ? `Monthly cost: ${formatCurrency(200)}` : 'Select a phone number'}
                </div>
                <div className="flex gap-3">
                  <button
                    onClick={() => setShowWizardPhoneModal(false)}
                    className="px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleWizardPhoneConfirm}
                    disabled={!wizardSelectedNumber}
                    className="px-6 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                  >
                    Continue
                    <ArrowRight className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
      </LockedSection>
    </div>
  );
};

export default CommunicationSettings;
