'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Phone,
  Search,
  ShoppingCart,
  Trash2,
  Settings,
  Globe,
  MessageSquare,
  PhoneCall,
  Mail,
  AlertTriangle,
  X,
  RefreshCw,
  Check,
  Loader2,
  Hash,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { formatPhone } from '@/lib/utils';

/* ------------------------------------------------------------------ */
/*  Types                                                              */
/* ------------------------------------------------------------------ */

interface OwnedNumber {
  sid: string;
  phoneNumber: string;
  friendlyName: string;
  smsEnabled: boolean;
  voiceEnabled: boolean;
  mmsEnabled: boolean;
  dateCreated: string;
  smsUrl: string | null;
  voiceUrl: string | null;
}

interface AvailableNumber {
  phoneNumber: string;
  friendlyName: string;
  locality: string;
  region: string;
  isoCountry: string;
  capabilities: {
    sms: boolean;
    voice: boolean;
    mms: boolean;
  };
}

/* ------------------------------------------------------------------ */
/*  Capability Badge                                                   */
/* ------------------------------------------------------------------ */

function CapBadge({ label, active }: { label: string; active: boolean }) {
  return (
    <span
      className={cn(
        'inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wider border',
        active
          ? 'bg-cyan-500/15 text-cyan-400 border-cyan-500/30'
          : 'bg-slate-700/30 text-slate-600 border-slate-700/40'
      )}
    >
      {label === 'SMS' && <MessageSquare className="h-2.5 w-2.5" />}
      {label === 'Voice' && <PhoneCall className="h-2.5 w-2.5" />}
      {label === 'MMS' && <Mail className="h-2.5 w-2.5" />}
      {label}
    </span>
  );
}

/* ------------------------------------------------------------------ */
/*  Confirmation Modal                                                 */
/* ------------------------------------------------------------------ */

function ConfirmModal({
  title,
  message,
  confirmLabel,
  danger,
  onConfirm,
  onCancel,
  loading,
}: {
  title: string;
  message: string;
  confirmLabel: string;
  danger?: boolean;
  onConfirm: () => void;
  onCancel: () => void;
  loading?: boolean;
}) {
  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm">
      <div className="card w-full max-w-md p-6 mx-4">
        <div className="flex items-start gap-3 mb-4">
          <div
            className={cn(
              'flex h-10 w-10 items-center justify-center rounded-full flex-shrink-0',
              danger ? 'bg-red-500/15' : 'bg-cyan-500/15'
            )}
          >
            {danger ? (
              <AlertTriangle className="h-5 w-5 text-red-400" />
            ) : (
              <ShoppingCart className="h-5 w-5 text-cyan-400" />
            )}
          </div>
          <div>
            <h3 className="text-white font-semibold text-lg">{title}</h3>
            <p className="text-slate-400 text-sm mt-1">{message}</p>
          </div>
        </div>

        <div className="flex items-center justify-end gap-3 mt-6">
          <button
            onClick={onCancel}
            disabled={loading}
            className="px-4 py-2 text-sm font-medium text-slate-400 hover:text-slate-200 bg-slate-800/50 hover:bg-slate-700/50 rounded-lg border border-slate-700/50 transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={onConfirm}
            disabled={loading}
            className={cn(
              'px-4 py-2 text-sm font-medium rounded-lg transition-all flex items-center gap-2',
              danger
                ? 'bg-red-500/20 text-red-400 hover:bg-red-500/30 border border-red-500/30'
                : 'bg-cyan-500/20 text-cyan-400 hover:bg-cyan-500/30 border border-cyan-500/30'
            )}
          >
            {loading && <Loader2 className="h-4 w-4 animate-spin" />}
            {confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Configure Modal                                                    */
/* ------------------------------------------------------------------ */

function ConfigureModal({
  number,
  onClose,
  onSaved,
}: {
  number: OwnedNumber;
  onClose: () => void;
  onSaved: () => void;
}) {
  const [friendlyName, setFriendlyName] = useState(number.friendlyName);
  const [smsUrl, setSmsUrl] = useState(number.smsUrl || '');
  const [voiceUrl, setVoiceUrl] = useState(number.voiceUrl || '');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const handleSave = async () => {
    setSaving(true);
    setError('');
    try {
      const res = await fetch(`/api/twilio/numbers/${number.sid}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ friendlyName, smsUrl: smsUrl || undefined, voiceUrl: voiceUrl || undefined }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Update failed');
      }
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Update failed');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm">
      <div className="card w-full max-w-lg p-6 mx-4">
        <div className="flex items-center justify-between mb-5">
          <div>
            <h3 className="text-white font-semibold text-lg">Configure Number</h3>
            <p className="text-cyan-400 text-sm font-mono mt-0.5">{formatPhone(number.phoneNumber)}</p>
          </div>
          <button onClick={onClose} className="text-slate-500 hover:text-slate-300 transition-colors">
            <X className="h-5 w-5" />
          </button>
        </div>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-300 mb-1.5">Friendly Name</label>
            <input
              type="text"
              value={friendlyName}
              onChange={(e) => setFriendlyName(e.target.value)}
              className="w-full px-3 py-2 bg-slate-800/50 border border-slate-700/50 rounded-lg text-white text-sm focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-colors"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-300 mb-1.5">SMS Webhook URL</label>
            <input
              type="url"
              value={smsUrl}
              onChange={(e) => setSmsUrl(e.target.value)}
              placeholder="https://..."
              className="w-full px-3 py-2 bg-slate-800/50 border border-slate-700/50 rounded-lg text-white text-sm placeholder:text-slate-600 focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-colors"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-slate-300 mb-1.5">Voice Webhook URL</label>
            <input
              type="url"
              value={voiceUrl}
              onChange={(e) => setVoiceUrl(e.target.value)}
              placeholder="https://..."
              className="w-full px-3 py-2 bg-slate-800/50 border border-slate-700/50 rounded-lg text-white text-sm placeholder:text-slate-600 focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-colors"
            />
          </div>
        </div>

        {error && (
          <p className="text-red-400 text-sm mt-3">{error}</p>
        )}

        <div className="flex items-center justify-end gap-3 mt-6">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-slate-400 hover:text-slate-200 bg-slate-800/50 hover:bg-slate-700/50 rounded-lg border border-slate-700/50 transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={saving}
            className="px-4 py-2 text-sm font-medium bg-cyan-500/20 text-cyan-400 hover:bg-cyan-500/30 rounded-lg border border-cyan-500/30 transition-all flex items-center gap-2"
          >
            {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
            Save Changes
          </button>
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Skeleton loader                                                    */
/* ------------------------------------------------------------------ */

function SkeletonRow() {
  return (
    <div className="flex items-center gap-4 p-4 animate-pulse">
      <div className="h-10 w-10 rounded-full bg-slate-700/50" />
      <div className="flex-1 space-y-2">
        <div className="h-4 w-36 bg-slate-700/50 rounded" />
        <div className="h-3 w-24 bg-slate-700/30 rounded" />
      </div>
      <div className="flex gap-2">
        <div className="h-5 w-12 bg-slate-700/30 rounded-full" />
        <div className="h-5 w-12 bg-slate-700/30 rounded-full" />
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Main Page                                                          */
/* ------------------------------------------------------------------ */

export default function PhoneNumbersPage() {
  /* --- State: owned numbers --- */
  const [ownedNumbers, setOwnedNumbers] = useState<OwnedNumber[]>([]);
  const [loadingOwned, setLoadingOwned] = useState(true);
  const [noCredentials, setNoCredentials] = useState(false);

  /* --- State: search --- */
  const [country, setCountry] = useState('US');
  const [areaCode, setAreaCode] = useState('');
  const [contains, setContains] = useState('');
  const [numberType, setNumberType] = useState<'local' | 'tollFree'>('local');
  const [smsEnabled, setSmsEnabled] = useState(true);
  const [voiceEnabled, setVoiceEnabled] = useState(false);
  const [mmsEnabled, setMmsEnabled] = useState(false);
  const [searchResults, setSearchResults] = useState<AvailableNumber[]>([]);
  const [searching, setSearching] = useState(false);
  const [searchError, setSearchError] = useState('');
  const [hasSearched, setHasSearched] = useState(false);

  /* --- State: modals --- */
  const [buyTarget, setBuyTarget] = useState<AvailableNumber | null>(null);
  const [releaseTarget, setReleaseTarget] = useState<OwnedNumber | null>(null);
  const [configureTarget, setConfigureTarget] = useState<OwnedNumber | null>(null);
  const [modalLoading, setModalLoading] = useState(false);

  /* --- Fetch owned numbers --- */
  const fetchOwned = useCallback(async () => {
    setLoadingOwned(true);
    try {
      const res = await fetch('/api/twilio/numbers');
      if (!res.ok) throw new Error('Failed to load');
      const data = await res.json();
      if (data.error && data.error.includes('credentials')) {
        setNoCredentials(true);
        setOwnedNumbers([]);
      } else {
        setNoCredentials(false);
        setOwnedNumbers(Array.isArray(data) ? data : []);
      }
    } catch {
      setOwnedNumbers([]);
    } finally {
      setLoadingOwned(false);
    }
  }, []);

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

  /* --- Search available --- */
  const handleSearch = async () => {
    setSearching(true);
    setSearchError('');
    setHasSearched(true);
    try {
      const params = new URLSearchParams({ country, type: numberType, limit: '20' });
      if (areaCode) params.set('areaCode', areaCode);
      if (contains) params.set('contains', contains);
      if (smsEnabled) params.set('smsEnabled', 'true');
      if (voiceEnabled) params.set('voiceEnabled', 'true');
      if (mmsEnabled) params.set('mmsEnabled', 'true');

      const res = await fetch(`/api/twilio/numbers/search?${params}`);
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Search failed');
      setSearchResults(data);
    } catch (err) {
      setSearchError(err instanceof Error ? err.message : 'Search failed');
      setSearchResults([]);
    } finally {
      setSearching(false);
    }
  };

  /* --- Buy number --- */
  const handleBuy = async () => {
    if (!buyTarget) return;
    setModalLoading(true);
    try {
      const res = await fetch('/api/twilio/numbers/buy', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phoneNumber: buyTarget.phoneNumber }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Purchase failed');
      }
      setBuyTarget(null);
      setSearchResults((prev) => prev.filter((n) => n.phoneNumber !== buyTarget.phoneNumber));
      fetchOwned();
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Purchase failed');
    } finally {
      setModalLoading(false);
    }
  };

  /* --- Release number --- */
  const handleRelease = async () => {
    if (!releaseTarget) return;
    setModalLoading(true);
    try {
      const res = await fetch(`/api/twilio/numbers/${releaseTarget.sid}`, { method: 'DELETE' });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || 'Release failed');
      }
      setReleaseTarget(null);
      fetchOwned();
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Release failed');
    } finally {
      setModalLoading(false);
    }
  };

  /* --- No credentials state --- */
  if (noCredentials) {
    return (
      <div className="min-h-screen p-6" style={{ background: 'var(--bg-primary)' }}>
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-white tracking-tight">Phone Numbers</h1>
          <p className="text-sm mt-1" style={{ color: 'var(--text-secondary)' }}>
            Manage your Twilio phone numbers — search, buy, and configure.
          </p>
        </div>
        <div className="card p-12 flex flex-col items-center justify-center text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-full bg-yellow-500/15 mb-4">
            <AlertTriangle className="h-8 w-8 text-yellow-400" />
          </div>
          <h2 className="text-lg font-semibold text-white mb-2">Twilio Not Configured</h2>
          <p className="text-slate-400 text-sm max-w-md">
            To manage phone numbers, configure your Twilio Account SID and Auth Token in the Settings page.
          </p>
          <a
            href="/settings"
            className="mt-6 inline-flex items-center gap-2 px-5 py-2.5 bg-cyan-500/20 text-cyan-400 hover:bg-cyan-500/30 rounded-lg border border-cyan-500/30 text-sm font-medium transition-all"
          >
            <Settings className="h-4 w-4" />
            Go to Settings
          </a>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen p-6" style={{ background: 'var(--bg-primary)' }}>
      {/* Header */}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight">Phone Numbers</h1>
          <p className="text-sm mt-1" style={{ color: 'var(--text-secondary)' }}>
            Manage your Twilio phone numbers — search, buy, and configure.
          </p>
        </div>
        <button
          onClick={fetchOwned}
          className="flex items-center gap-2 px-3 py-2 text-sm text-slate-400 hover:text-slate-200 bg-slate-800/50 hover:bg-slate-700/50 rounded-lg border border-slate-700/50 transition-colors"
        >
          <RefreshCw className={cn('h-4 w-4', loadingOwned && 'animate-spin')} />
          Refresh
        </button>
      </div>

      {/* ============================================================ */}
      {/*  YOUR NUMBERS                                                 */}
      {/* ============================================================ */}
      <div className="card p-0 mb-6 overflow-hidden">
        <div className="flex items-center gap-3 px-5 py-4 border-b border-slate-700/40">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-cyan-500/10">
            <Phone className="h-4 w-4 text-cyan-400" />
          </div>
          <div>
            <h2 className="text-white font-semibold text-[15px]">Your Numbers</h2>
            <p className="text-slate-500 text-xs">
              {ownedNumbers.length} number{ownedNumbers.length !== 1 ? 's' : ''} on your account
            </p>
          </div>
        </div>

        {loadingOwned ? (
          <div className="divide-y divide-slate-700/30">
            <SkeletonRow />
            <SkeletonRow />
            <SkeletonRow />
          </div>
        ) : ownedNumbers.length === 0 ? (
          <div className="p-10 text-center">
            <Phone className="h-10 w-10 text-slate-700 mx-auto mb-3" />
            <p className="text-slate-500 text-sm">No phone numbers yet. Search and buy one below!</p>
          </div>
        ) : (
          <div className="divide-y divide-slate-700/30">
            {ownedNumbers.map((num) => (
              <div
                key={num.sid}
                className="flex items-center gap-4 px-5 py-4 hover:bg-slate-800/30 transition-colors"
              >
                {/* Icon */}
                <div className="flex h-10 w-10 items-center justify-center rounded-full bg-cyan-500/10 flex-shrink-0">
                  <Phone className="h-5 w-5 text-cyan-400" />
                </div>

                {/* Info */}
                <div className="flex-1 min-w-0">
                  <p className="text-white font-medium text-sm font-mono">
                    {formatPhone(num.phoneNumber)}
                  </p>
                  <p className="text-slate-500 text-xs mt-0.5 truncate">
                    {num.friendlyName}
                    {num.dateCreated && (
                      <span className="text-slate-600 ml-2">
                        · Purchased {new Date(num.dateCreated).toLocaleDateString()}
                      </span>
                    )}
                  </p>
                </div>

                {/* Capabilities */}
                <div className="hidden sm:flex items-center gap-1.5">
                  <CapBadge label="SMS" active={num.smsEnabled} />
                  <CapBadge label="Voice" active={num.voiceEnabled} />
                  <CapBadge label="MMS" active={num.mmsEnabled} />
                </div>

                {/* Actions */}
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => setConfigureTarget(num)}
                    className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-slate-400 hover:text-cyan-400 bg-slate-800/50 hover:bg-cyan-500/10 rounded-lg border border-slate-700/50 hover:border-cyan-500/30 transition-all"
                  >
                    <Settings className="h-3.5 w-3.5" />
                    Configure
                  </button>
                  <button
                    onClick={() => setReleaseTarget(num)}
                    className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-slate-500 hover:text-red-400 bg-slate-800/50 hover:bg-red-500/10 rounded-lg border border-slate-700/50 hover:border-red-500/30 transition-all"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                    Release
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* ============================================================ */}
      {/*  SEARCH & BUY                                                 */}
      {/* ============================================================ */}
      <div className="card p-0 overflow-hidden">
        <div className="flex items-center gap-3 px-5 py-4 border-b border-slate-700/40">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-cyan-500/10">
            <Search className="h-4 w-4 text-cyan-400" />
          </div>
          <div>
            <h2 className="text-white font-semibold text-[15px]">Search &amp; Buy Numbers</h2>
            <p className="text-slate-500 text-xs">Find available Twilio phone numbers to purchase</p>
          </div>
        </div>

        {/* Search form */}
        <div className="px-5 py-5 border-b border-slate-700/40">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Country */}
            <div>
              <label className="block text-xs font-medium text-slate-400 mb-1.5">
                <Globe className="h-3 w-3 inline mr-1" />
                Country
              </label>
              <select
                value={country}
                onChange={(e) => setCountry(e.target.value)}
                className="w-full px-3 py-2 bg-slate-800/50 border border-slate-700/50 rounded-lg text-white text-sm focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-colors"
              >
                <option value="US">🇺🇸 United States</option>
                <option value="CA">🇨🇦 Canada</option>
                <option value="GB">🇬🇧 United Kingdom</option>
                <option value="AU">🇦🇺 Australia</option>
              </select>
            </div>

            {/* Area code */}
            <div>
              <label className="block text-xs font-medium text-slate-400 mb-1.5">
                <Hash className="h-3 w-3 inline mr-1" />
                Area Code
              </label>
              <input
                type="text"
                value={areaCode}
                onChange={(e) => setAreaCode(e.target.value.replace(/\D/g, '').slice(0, 3))}
                placeholder="e.g. 212"
                maxLength={3}
                className="w-full px-3 py-2 bg-slate-800/50 border border-slate-700/50 rounded-lg text-white text-sm placeholder:text-slate-600 focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-colors"
              />
            </div>

            {/* Contains */}
            <div>
              <label className="block text-xs font-medium text-slate-400 mb-1.5">
                <Search className="h-3 w-3 inline mr-1" />
                Contains
              </label>
              <input
                type="text"
                value={contains}
                onChange={(e) => setContains(e.target.value)}
                placeholder="e.g. PIZZA"
                className="w-full px-3 py-2 bg-slate-800/50 border border-slate-700/50 rounded-lg text-white text-sm placeholder:text-slate-600 focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-colors"
              />
            </div>

            {/* Type */}
            <div>
              <label className="block text-xs font-medium text-slate-400 mb-1.5">
                <Phone className="h-3 w-3 inline mr-1" />
                Number Type
              </label>
              <select
                value={numberType}
                onChange={(e) => setNumberType(e.target.value as 'local' | 'tollFree')}
                className="w-full px-3 py-2 bg-slate-800/50 border border-slate-700/50 rounded-lg text-white text-sm focus:outline-none focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 transition-colors"
              >
                <option value="local">Local</option>
                <option value="tollFree">Toll-Free</option>
              </select>
            </div>
          </div>

          {/* Capabilities checkboxes + Search button */}
          <div className="flex flex-wrap items-center gap-6 mt-4">
            <div className="flex items-center gap-4">
              <label className="flex items-center gap-2 cursor-pointer group">
                <input
                  type="checkbox"
                  checked={smsEnabled}
                  onChange={(e) => setSmsEnabled(e.target.checked)}
                  className="h-4 w-4 rounded bg-slate-800 border-slate-600 text-cyan-500 focus:ring-cyan-500/30 focus:ring-offset-0"
                />
                <span className="text-sm text-slate-400 group-hover:text-slate-300 transition-colors">SMS</span>
              </label>
              <label className="flex items-center gap-2 cursor-pointer group">
                <input
                  type="checkbox"
                  checked={voiceEnabled}
                  onChange={(e) => setVoiceEnabled(e.target.checked)}
                  className="h-4 w-4 rounded bg-slate-800 border-slate-600 text-cyan-500 focus:ring-cyan-500/30 focus:ring-offset-0"
                />
                <span className="text-sm text-slate-400 group-hover:text-slate-300 transition-colors">Voice</span>
              </label>
              <label className="flex items-center gap-2 cursor-pointer group">
                <input
                  type="checkbox"
                  checked={mmsEnabled}
                  onChange={(e) => setMmsEnabled(e.target.checked)}
                  className="h-4 w-4 rounded bg-slate-800 border-slate-600 text-cyan-500 focus:ring-cyan-500/30 focus:ring-offset-0"
                />
                <span className="text-sm text-slate-400 group-hover:text-slate-300 transition-colors">MMS</span>
              </label>
            </div>

            <button
              onClick={handleSearch}
              disabled={searching}
              className="ml-auto flex items-center gap-2 px-5 py-2.5 bg-cyan-500/20 text-cyan-400 hover:bg-cyan-500/30 rounded-lg border border-cyan-500/30 text-sm font-medium transition-all disabled:opacity-50"
            >
              {searching ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Search className="h-4 w-4" />
              )}
              Search Available
            </button>
          </div>
        </div>

        {/* Search results */}
        <div className="p-5">
          {searchError && (
            <div className="flex items-center gap-2 p-3 mb-4 bg-red-500/10 border border-red-500/20 rounded-lg">
              <AlertTriangle className="h-4 w-4 text-red-400 flex-shrink-0" />
              <p className="text-red-400 text-sm">{searchError}</p>
            </div>
          )}

          {searching ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
              {Array.from({ length: 6 }).map((_, i) => (
                <div key={i} className="p-4 bg-slate-800/30 rounded-lg border border-slate-700/30 animate-pulse">
                  <div className="h-5 w-32 bg-slate-700/50 rounded mb-2" />
                  <div className="h-3 w-24 bg-slate-700/30 rounded mb-3" />
                  <div className="flex gap-1.5">
                    <div className="h-5 w-12 bg-slate-700/30 rounded-full" />
                    <div className="h-5 w-12 bg-slate-700/30 rounded-full" />
                  </div>
                </div>
              ))}
            </div>
          ) : searchResults.length > 0 ? (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
              {searchResults.map((num) => (
                <div
                  key={num.phoneNumber}
                  className="group p-4 bg-slate-800/30 hover:bg-slate-800/50 rounded-lg border border-slate-700/30 hover:border-cyan-500/20 transition-all"
                >
                  <p className="text-white font-medium text-sm font-mono">
                    {formatPhone(num.phoneNumber)}
                  </p>
                  <p className="text-slate-500 text-xs mt-0.5">
                    {num.locality && num.region
                      ? `${num.locality}, ${num.region}`
                      : num.friendlyName}
                  </p>

                  <div className="flex items-center gap-1.5 mt-3">
                    <CapBadge label="SMS" active={num.capabilities.sms} />
                    <CapBadge label="Voice" active={num.capabilities.voice} />
                    <CapBadge label="MMS" active={num.capabilities.mms} />
                  </div>

                  <button
                    onClick={() => setBuyTarget(num)}
                    className="mt-3 w-full flex items-center justify-center gap-2 px-3 py-2 bg-cyan-500/10 hover:bg-cyan-500/20 text-cyan-400 rounded-lg border border-cyan-500/20 hover:border-cyan-500/40 text-xs font-medium transition-all opacity-70 group-hover:opacity-100"
                  >
                    <ShoppingCart className="h-3.5 w-3.5" />
                    Buy This Number
                  </button>
                </div>
              ))}
            </div>
          ) : hasSearched && !searchError ? (
            <div className="text-center py-8">
              <Search className="h-10 w-10 text-slate-700 mx-auto mb-3" />
              <p className="text-slate-500 text-sm">No numbers found. Try adjusting your search criteria.</p>
            </div>
          ) : (
            <div className="text-center py-8">
              <Globe className="h-10 w-10 text-slate-700 mx-auto mb-3" />
              <p className="text-slate-500 text-sm">Search for available phone numbers above</p>
            </div>
          )}
        </div>
      </div>

      {/* ============================================================ */}
      {/*  MODALS                                                       */}
      {/* ============================================================ */}
      {buyTarget && (
        <ConfirmModal
          title="Purchase Phone Number"
          message={`Are you sure you want to purchase ${formatPhone(buyTarget.phoneNumber)}? This will be billed to your Twilio account.`}
          confirmLabel="Purchase Number"
          onConfirm={handleBuy}
          onCancel={() => setBuyTarget(null)}
          loading={modalLoading}
        />
      )}

      {releaseTarget && (
        <ConfirmModal
          title="Release Phone Number"
          message={`Are you sure you want to release ${formatPhone(releaseTarget.phoneNumber)}? This action cannot be undone and you may not be able to get this number back.`}
          confirmLabel="Release Number"
          danger
          onConfirm={handleRelease}
          onCancel={() => setReleaseTarget(null)}
          loading={modalLoading}
        />
      )}

      {configureTarget && (
        <ConfigureModal
          number={configureTarget}
          onClose={() => setConfigureTarget(null)}
          onSaved={fetchOwned}
        />
      )}
    </div>
  );
}
