import React, { useState } from 'react';
import {
  Search,
  Globe,
  Check,
  X,
  ShoppingCart,
  Loader2,
  ChevronRight,
  Shield,
  RefreshCw,
  AlertCircle,
} from 'lucide-react';
import {
  useDomainSearch,
  useRegisterDomain,
  useRegisteredDomains,
  type DomainAvailability,
  type RegistrantContact,
} from '../hooks/useDomains';

interface DomainPurchaseProps {
  onSuccess?: () => void;
}

type Step = 'search' | 'details' | 'confirm';

const DomainPurchase: React.FC<DomainPurchaseProps> = ({ onSuccess }) => {
  const [step, setStep] = useState<Step>('search');
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<DomainAvailability[]>([]);
  const [selectedDomain, setSelectedDomain] = useState<DomainAvailability | null>(null);
  const [years, setYears] = useState(1);
  const [whoisPrivacy, setWhoisPrivacy] = useState(true);
  const [autoRenew, setAutoRenew] = useState(true);
  const [autoConfigureDomain, setAutoConfigureDomain] = useState(true);

  // Contact info form state
  const [contact, setContact] = useState<RegistrantContact>({
    first_name: '',
    last_name: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    state: '',
    zip_code: '',
    country: 'US',
  });

  const searchMutation = useDomainSearch();
  const registerMutation = useRegisterDomain();
  const { data: registeredDomains } = useRegisteredDomains();

  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!searchQuery.trim()) return;

    try {
      const results = await searchMutation.mutateAsync({
        query: searchQuery,
        tlds: ['.com', '.net', '.org', '.io', '.co'],
      });
      setSearchResults(results);
    } catch {
      // Error is handled by React Query
    }
  };

  const handleSelectDomain = (domain: DomainAvailability) => {
    setSelectedDomain(domain);
    setStep('details');
  };

  const handlePurchase = async () => {
    if (!selectedDomain) return;

    try {
      await registerMutation.mutateAsync({
        domain: selectedDomain.domain,
        years,
        whois_privacy: whoisPrivacy,
        auto_renew: autoRenew,
        contact,
        auto_configure: autoConfigureDomain,
      });

      // Reset and go back to search
      setStep('search');
      setSearchQuery('');
      setSearchResults([]);
      setSelectedDomain(null);
      onSuccess?.();
    } catch {
      // Error is handled by React Query
    }
  };

  const updateContact = (field: keyof RegistrantContact, value: string) => {
    setContact((prev) => ({ ...prev, [field]: value }));
  };

  const isContactValid = () => {
    return (
      contact.first_name &&
      contact.last_name &&
      contact.email &&
      contact.phone &&
      contact.address &&
      contact.city &&
      contact.state &&
      contact.zip_code &&
      contact.country
    );
  };

  const getPrice = () => {
    if (!selectedDomain) return 0;
    const basePrice = selectedDomain.premium_price || selectedDomain.price || 0;
    return basePrice * years;
  };

  return (
    <div className="space-y-6">
      {/* Steps indicator */}
      <div className="flex items-center gap-4">
        <div
          className={`flex items-center gap-2 ${
            step === 'search' ? 'text-brand-600 dark:text-brand-400' : 'text-gray-400'
          }`}
        >
          <div
            className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium ${
              step === 'search'
                ? 'bg-brand-600 text-white'
                : 'bg-gray-200 dark:bg-gray-700 text-gray-500'
            }`}
          >
            1
          </div>
          <span className="text-sm font-medium">Search</span>
        </div>
        <ChevronRight className="h-4 w-4 text-gray-400" />
        <div
          className={`flex items-center gap-2 ${
            step === 'details' ? 'text-brand-600 dark:text-brand-400' : 'text-gray-400'
          }`}
        >
          <div
            className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium ${
              step === 'details'
                ? 'bg-brand-600 text-white'
                : 'bg-gray-200 dark:bg-gray-700 text-gray-500'
            }`}
          >
            2
          </div>
          <span className="text-sm font-medium">Details</span>
        </div>
        <ChevronRight className="h-4 w-4 text-gray-400" />
        <div
          className={`flex items-center gap-2 ${
            step === 'confirm' ? 'text-brand-600 dark:text-brand-400' : 'text-gray-400'
          }`}
        >
          <div
            className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium ${
              step === 'confirm'
                ? 'bg-brand-600 text-white'
                : 'bg-gray-200 dark:bg-gray-700 text-gray-500'
            }`}
          >
            3
          </div>
          <span className="text-sm font-medium">Confirm</span>
        </div>
      </div>

      {/* Step 1: Search */}
      {step === 'search' && (
        <div className="space-y-6">
          <form onSubmit={handleSearch} className="flex gap-3">
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Enter domain name or keyword..."
                className="w-full pl-10 pr-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 focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
              />
            </div>
            <button
              type="submit"
              disabled={searchMutation.isPending || !searchQuery.trim()}
              className="px-6 py-3 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {searchMutation.isPending ? (
                <Loader2 className="h-5 w-5 animate-spin" />
              ) : (
                <Search className="h-5 w-5" />
              )}
              Search
            </button>
          </form>

          {/* Search Results */}
          {searchResults.length > 0 && (
            <div className="space-y-3">
              <h4 className="font-medium text-gray-900 dark:text-white">Search Results</h4>
              <div className="space-y-2">
                {searchResults.map((result) => (
                  <div
                    key={result.domain}
                    className={`flex items-center justify-between p-4 rounded-lg border ${
                      result.available
                        ? 'border-green-200 dark:border-green-900 bg-green-50 dark:bg-green-900/20'
                        : 'border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50'
                    }`}
                  >
                    <div className="flex items-center gap-3">
                      {result.available ? (
                        <Check className="h-5 w-5 text-green-600 dark:text-green-400" />
                      ) : (
                        <X className="h-5 w-5 text-gray-400" />
                      )}
                      <div>
                        <span className="font-medium text-gray-900 dark:text-white">
                          {result.domain}
                        </span>
                        {result.premium && (
                          <span className="ml-2 px-2 py-0.5 text-xs bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400 rounded">
                            Premium
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center gap-4">
                      {result.available && (
                        <>
                          <span className="font-semibold text-gray-900 dark:text-white">
                            ${(result.premium_price || result.price || 0).toFixed(2)}/yr
                          </span>
                          <button
                            onClick={() => handleSelectDomain(result)}
                            className="px-4 py-2 bg-brand-600 text-white text-sm rounded-lg hover:bg-brand-700 flex items-center gap-2"
                          >
                            <ShoppingCart className="h-4 w-4" />
                            Select
                          </button>
                        </>
                      )}
                      {!result.available && (
                        <span className="text-sm text-gray-500 dark:text-gray-400">Unavailable</span>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Registered Domains */}
          {registeredDomains && registeredDomains.length > 0 && (
            <div className="mt-8 pt-6 border-t border-gray-100 dark:border-gray-700">
              <h4 className="font-medium text-gray-900 dark:text-white mb-4">
                Your Registered Domains
              </h4>
              <div className="space-y-2">
                {registeredDomains.map((domain) => (
                  <div
                    key={domain.id}
                    className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg"
                  >
                    <div className="flex items-center gap-3">
                      <Globe className="h-5 w-5 text-gray-400" />
                      <span className="font-medium text-gray-900 dark:text-white">
                        {domain.domain}
                      </span>
                      <span
                        className={`px-2 py-0.5 text-xs rounded ${
                          domain.status === 'active'
                            ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
                            : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300'
                        }`}
                      >
                        {domain.status}
                      </span>
                    </div>
                    {domain.expires_at && (
                      <span className="text-sm text-gray-500 dark:text-gray-400">
                        Expires: {new Date(domain.expires_at).toLocaleDateString()}
                      </span>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Step 2: Details */}
      {step === 'details' && selectedDomain && (
        <div className="space-y-6">
          {/* Selected Domain */}
          <div className="p-4 bg-brand-50 dark:bg-brand-900/20 rounded-lg border border-brand-200 dark:border-brand-800">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Globe className="h-6 w-6 text-brand-600 dark:text-brand-400" />
                <span className="text-lg font-semibold text-gray-900 dark:text-white">
                  {selectedDomain.domain}
                </span>
              </div>
              <button
                onClick={() => setStep('search')}
                className="text-sm text-brand-600 dark:text-brand-400 hover:underline"
              >
                Change
              </button>
            </div>
          </div>

          {/* Registration Options */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                Registration Period
              </label>
              <select
                value={years}
                onChange={(e) => setYears(Number(e.target.value))}
                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"
              >
                {[1, 2, 3, 5, 10].map((y) => (
                  <option key={y} value={y}>
                    {y} {y === 1 ? 'year' : 'years'} - $
                    {((selectedDomain.premium_price || selectedDomain.price || 0) * y).toFixed(2)}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Privacy & Auto-renew */}
          <div className="space-y-4">
            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                checked={whoisPrivacy}
                onChange={(e) => setWhoisPrivacy(e.target.checked)}
                className="w-5 h-5 rounded border-gray-300 text-brand-600 focus:ring-brand-500"
              />
              <div className="flex items-center gap-2">
                <Shield className="h-5 w-5 text-gray-400" />
                <div>
                  <span className="text-gray-900 dark:text-white font-medium">
                    WHOIS Privacy Protection
                  </span>
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    Hide your personal information from public WHOIS lookups
                  </p>
                </div>
              </div>
            </label>

            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                checked={autoRenew}
                onChange={(e) => setAutoRenew(e.target.checked)}
                className="w-5 h-5 rounded border-gray-300 text-brand-600 focus:ring-brand-500"
              />
              <div className="flex items-center gap-2">
                <RefreshCw className="h-5 w-5 text-gray-400" />
                <div>
                  <span className="text-gray-900 dark:text-white font-medium">Auto-Renewal</span>
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    Automatically renew this domain before it expires
                  </p>
                </div>
              </div>
            </label>

            <label className="flex items-center gap-3 cursor-pointer">
              <input
                type="checkbox"
                checked={autoConfigureDomain}
                onChange={(e) => setAutoConfigureDomain(e.target.checked)}
                className="w-5 h-5 rounded border-gray-300 text-brand-600 focus:ring-brand-500"
              />
              <div className="flex items-center gap-2">
                <Globe className="h-5 w-5 text-gray-400" />
                <div>
                  <span className="text-gray-900 dark:text-white font-medium">
                    Auto-configure as Custom Domain
                  </span>
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    Automatically set up this domain for your business
                  </p>
                </div>
              </div>
            </label>
          </div>

          {/* Contact Information */}
          <div className="pt-6 border-t border-gray-100 dark:border-gray-700">
            <h4 className="font-medium text-gray-900 dark:text-white mb-4">
              Registrant Information
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  First Name *
                </label>
                <input
                  type="text"
                  value={contact.first_name}
                  onChange={(e) => updateContact('first_name', e.target.value)}
                  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"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Last Name *
                </label>
                <input
                  type="text"
                  value={contact.last_name}
                  onChange={(e) => updateContact('last_name', e.target.value)}
                  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"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Email *
                </label>
                <input
                  type="email"
                  value={contact.email}
                  onChange={(e) => updateContact('email', e.target.value)}
                  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"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Phone *
                </label>
                <input
                  type="tel"
                  value={contact.phone}
                  onChange={(e) => updateContact('phone', e.target.value)}
                  placeholder="+1.5551234567"
                  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"
                  required
                />
              </div>
              <div className="md:col-span-2">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Address *
                </label>
                <input
                  type="text"
                  value={contact.address}
                  onChange={(e) => updateContact('address', e.target.value)}
                  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"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  City *
                </label>
                <input
                  type="text"
                  value={contact.city}
                  onChange={(e) => updateContact('city', e.target.value)}
                  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"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  State/Province *
                </label>
                <input
                  type="text"
                  value={contact.state}
                  onChange={(e) => updateContact('state', e.target.value)}
                  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"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  ZIP/Postal Code *
                </label>
                <input
                  type="text"
                  value={contact.zip_code}
                  onChange={(e) => updateContact('zip_code', e.target.value)}
                  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"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Country *
                </label>
                <select
                  value={contact.country}
                  onChange={(e) => updateContact('country', e.target.value)}
                  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"
                >
                  <option value="US">United States</option>
                  <option value="CA">Canada</option>
                  <option value="GB">United Kingdom</option>
                  <option value="AU">Australia</option>
                  <option value="DE">Germany</option>
                  <option value="FR">France</option>
                </select>
              </div>
            </div>
          </div>

          {/* Actions */}
          <div className="flex justify-between pt-4">
            <button
              onClick={() => setStep('search')}
              className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
            >
              Back
            </button>
            <button
              onClick={() => setStep('confirm')}
              disabled={!isContactValid()}
              className="px-6 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Continue
            </button>
          </div>
        </div>
      )}

      {/* Step 3: Confirm */}
      {step === 'confirm' && selectedDomain && (
        <div className="space-y-6">
          <h4 className="font-medium text-gray-900 dark:text-white">Order Summary</h4>

          <div className="bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4 space-y-3">
            <div className="flex justify-between">
              <span className="text-gray-600 dark:text-gray-400">Domain</span>
              <span className="font-medium text-gray-900 dark:text-white">
                {selectedDomain.domain}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600 dark:text-gray-400">Registration Period</span>
              <span className="font-medium text-gray-900 dark:text-white">
                {years} {years === 1 ? 'year' : 'years'}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600 dark:text-gray-400">WHOIS Privacy</span>
              <span className="font-medium text-gray-900 dark:text-white">
                {whoisPrivacy ? 'Enabled' : 'Disabled'}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-600 dark:text-gray-400">Auto-Renewal</span>
              <span className="font-medium text-gray-900 dark:text-white">
                {autoRenew ? 'Enabled' : 'Disabled'}
              </span>
            </div>
            <div className="pt-3 border-t border-gray-200 dark:border-gray-700">
              <div className="flex justify-between">
                <span className="font-semibold text-gray-900 dark:text-white">Total</span>
                <span className="font-bold text-xl text-brand-600 dark:text-brand-400">
                  ${getPrice().toFixed(2)}
                </span>
              </div>
            </div>
          </div>

          {/* Registrant Summary */}
          <div className="bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4">
            <h5 className="font-medium text-gray-900 dark:text-white mb-2">Registrant</h5>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              {contact.first_name} {contact.last_name}
              <br />
              {contact.email}
              <br />
              {contact.address}
              <br />
              {contact.city}, {contact.state} {contact.zip_code}
            </p>
          </div>

          {registerMutation.isError && (
            <div className="flex items-center gap-2 p-4 bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400 rounded-lg">
              <AlertCircle className="h-5 w-5" />
              <span>Registration failed. Please try again.</span>
            </div>
          )}

          {/* Actions */}
          <div className="flex justify-between pt-4">
            <button
              onClick={() => setStep('details')}
              className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
            >
              Back
            </button>
            <button
              onClick={handlePurchase}
              disabled={registerMutation.isPending}
              className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {registerMutation.isPending ? (
                <Loader2 className="h-5 w-5 animate-spin" />
              ) : (
                <ShoppingCart className="h-5 w-5" />
              )}
              Complete Purchase
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default DomainPurchase;
