'use client';

import { useState } from 'react';
import Link from 'next/link';
import { Search, Phone, ArrowLeft, CheckCircle, ShoppingCart, Loader2 } from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { searchTwilioNumbers, purchaseTwilioNumber } from '@client/api/telephone';
import type { AvailableTwilioNumber } from '@client/api/telephone';
import { toast } from 'sonner';
import { useLanguage } from '@client/contexts/LanguageContext';

type NumberType = 'local' | 'toll-free' | 'mobile';

const countries = [
  { code: 'US', name: 'United States', flag: '\u{1F1FA}\u{1F1F8}' },
  { code: 'GB', name: 'United Kingdom', flag: '\u{1F1EC}\u{1F1E7}' },
  { code: 'CA', name: 'Canada', flag: '\u{1F1E8}\u{1F1E6}' },
  { code: 'AU', name: 'Australia', flag: '\u{1F1E6}\u{1F1FA}' },
  { code: 'DE', name: 'Germany', flag: '\u{1F1E9}\u{1F1EA}' },
  { code: 'FR', name: 'France', flag: '\u{1F1EB}\u{1F1F7}' },
];

export default function BuyPhoneNumberPage() {
  const { t } = useLanguage();
  usePageHeader(t('phoneNumbers.buy.title', "Buy Phone Number"), t('phoneNumbers.buy.subtitle', "Search and purchase a new Twilio phone number"));
  const [country, setCountry] = useState('US');
  const [areaCode, setAreaCode] = useState('');
  const [numberType, setNumberType] = useState<NumberType>('local');
  const [searching, setSearching] = useState(false);
  const [results, setResults] = useState<AvailableTwilioNumber[]>([]);
  const [searched, setSearched] = useState(false);
  const [selectedNumber, setSelectedNumber] = useState<AvailableTwilioNumber | null>(null);
  const [purchasing, setPurchasing] = useState(false);
  const [purchased, setPurchased] = useState(false);
  const [purchasedNumber, setPurchasedNumber] = useState('');

  const handleSearch = async () => {
    setSearching(true);
    setResults([]);
    setSelectedNumber(null);
    try {
      const res = await searchTwilioNumbers(country, { areaCode: areaCode || undefined, type: numberType, limit: 20 });
      setResults(res.numbers || []);
      setSearched(true);
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : 'Search failed');
    } finally {
      setSearching(false);
    }
  };

  const handlePurchase = async () => {
    if (!selectedNumber) return;
    setPurchasing(true);
    try {
      const res = await purchaseTwilioNumber(selectedNumber.phone_number);
      if (res.success) {
        setPurchased(true);
        setPurchasedNumber(res.phone_number || selectedNumber.phone_number);
        toast.success(t('phoneNumbers.purchasedSuccessfully', 'Number purchased successfully!'));
      }
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t('phoneNumbers.purchaseFailed', 'Purchase failed'));
    } finally {
      setPurchasing(false);
    }
  };

  if (purchased) {
    return (
      <div className="max-w-md mx-auto text-center py-12">
        <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4" style={{ backgroundColor: 'hsl(142, 72%, 96%)' }}>
          <CheckCircle size={32} style={{ color: 'hsl(142, 72%, 29%)' }} />
        </div>
        <h2 className="text-xl font-bold mb-2" style={{ color: 'hsl(var(--foreground))' }}>{t('phoneNumbers.buy.successTitle', 'Number Purchased!')}</h2>
        <p className="text-sm mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('phoneNumbers.buy.successMessage', 'Your new number is active and webhooks are configured:')}</p>
        <p className="text-2xl font-mono font-bold mb-6" style={{ color: 'hsl(var(--primary))' }}>{purchasedNumber}</p>
        <div className="flex gap-3 justify-center">
          <Link href="/telephone" className="btn-primary">{t('phoneNumbers.buy.manageNumbers', 'Manage Numbers')}</Link>
          <Link href="/ai-agent-config/phone-numbers" className="btn-secondary">{t('phoneNumbers.buy.viewAllNumbers', 'View All Numbers')}</Link>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-3xl">
      <Link href="/ai-agent-config/phone-numbers" className="flex items-center gap-2 text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>
        <ArrowLeft size={15} /> {t('phoneNumbers.buy.backLink', 'Back to Phone Numbers')}
      </Link>

      <div className="rounded-2xl p-5 mb-6" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        <h3 className="font-semibold text-sm mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('phoneNumbers.buy.searchTitle', 'Search Available Numbers')}</h3>
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-4">
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('phoneNumbers.buy.country', 'Country')}</label>
            <select value={country} onChange={e => setCountry(e.target.value)} className="input-field w-full">
              {countries.map(c => <option key={c.code} value={c.code}>{c.flag} {c.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('phoneNumbers.buy.areaCode', 'Area Code (optional)')}</label>
            <input type="text" placeholder={t('phoneNumbers.buy.areaCodePlaceholder', "e.g. 415")} value={areaCode} onChange={e => setAreaCode(e.target.value)} className="input-field w-full" />
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('phoneNumbers.buy.numberType', 'Number Type')}</label>
            <select value={numberType} onChange={e => setNumberType(e.target.value as NumberType)} className="input-field w-full">
              <option value="local">{t('phoneNumbers.buy.typeLocal', 'Local')}</option>
              <option value="toll-free">{t('phoneNumbers.buy.typeTollFree', 'Toll-Free')}</option>
              <option value="mobile">{t('phoneNumbers.buy.typeMobile', 'Mobile')}</option>
            </select>
          </div>
        </div>
        <button className="btn-primary" onClick={handleSearch} disabled={searching}>
          {searching ? <Loader2 size={15} className="animate-spin" /> : <Search size={15} />} {searching ? t('phoneNumbers.buy.searching', 'Searching...') : t('phoneNumbers.buy.searchButton', 'Search Numbers')}
        </button>
      </div>

      {searched && (
        <div>
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
              {t('phoneNumbers.buy.availableNumbers', 'Available Numbers')} <span className="font-normal" style={{ color: 'hsl(var(--muted-foreground))' }}>({results.length} {t('phoneNumbers.buy.found', 'found')})</span>
            </h3>
          </div>
          <div className="space-y-2">
            {results.map(num => {
              const isSelected = selectedNumber?.phone_number === num.phone_number;
              const caps = Object.entries(num.capabilities || {}).filter(([, v]) => v).map(([k]) => k).join(', ');
              return (
                <div
                  key={num.phone_number}
                  className="flex items-center gap-4 p-4 rounded-xl cursor-pointer transition-all"
                  style={{
                    backgroundColor: isSelected ? 'hsl(var(--primary-light))' : 'hsl(var(--surface))',
                    border: `1px solid ${isSelected ? 'hsl(var(--primary))' : 'hsl(var(--border))'}`,
                  }}
                  onClick={() => setSelectedNumber(isSelected ? null : num)}
                >
                  <div className="flex-1 min-w-0">
                    <span className="font-mono font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{num.phone_number}</span>
                    {(num.locality || num.region) && (
                      <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{[num.locality, num.region].filter(Boolean).join(', ')}</p>
                    )}
                  </div>
                  <div className="text-right shrink-0">
                    <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{caps || 'Voice'}</p>
                  </div>
                  {isSelected && <CheckCircle size={18} style={{ color: 'hsl(var(--primary))', flexShrink: 0 }} />}
                </div>
              );
            })}
            {results.length === 0 && (
              <div className="text-center py-10" style={{ color: 'hsl(var(--muted-foreground))' }}>
                <Phone size={28} className="mx-auto mb-2 opacity-30" />
                <p className="text-sm">{t('phoneNumbers.buy.noNumbersFound', 'No numbers found. Try a different area code or country.')}</p>
              </div>
            )}
          </div>
          {selectedNumber && (
            <div className="mt-4 flex justify-end">
              <button className="btn-primary" onClick={handlePurchase} disabled={purchasing}>
                {purchasing ? <Loader2 size={15} className="animate-spin" /> : <ShoppingCart size={15} />}
                {purchasing ? t('phoneNumbers.buy.purchasing', 'Purchasing...') : `${t('phoneNumbers.buy.purchaseButton', 'Purchase')} ${selectedNumber.phone_number}`}
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
