import React, { useState } from 'react';
import { X, Search, MapPin, Check } from 'lucide-react';
import { Button } from './ui/button';

interface Address {
  id: number;
  label: string;
  type: 'billing' | 'shipping' | 'both';
  first_name: string;
  last_name: string;
  company?: string;
  address_1: string;
  address_2?: string;
  city: string;
  state: string;
  postcode: string;
  country: string;
  email?: string;
  phone?: string;
  is_default: boolean;
}

interface AddressSelectorProps {
  isOpen: boolean;
  onClose: () => void;
  addresses: Address[];
  selectedAddressId: number | null;
  onSelectAddress: (address: Address) => void;
  type: 'billing' | 'shipping';
}

export function AddressSelector({
  isOpen,
  onClose,
  addresses,
  selectedAddressId,
  onSelectAddress,
  type,
}: AddressSelectorProps) {
  const [searchQuery, setSearchQuery] = useState('');

  if (!isOpen) return null;

  // Filter addresses by type and search query
  const filteredAddresses = addresses
    .filter(a => a.type === type || a.type === 'both')
    .filter(a => {
      if (!searchQuery) return true;
      const query = searchQuery.toLowerCase();
      return (
        a.label.toLowerCase().includes(query) ||
        a.first_name.toLowerCase().includes(query) ||
        a.last_name.toLowerCase().includes(query) ||
        a.address_1.toLowerCase().includes(query) ||
        a.city.toLowerCase().includes(query)
      );
    });

  const handleSelect = (address: Address) => {
    onSelectAddress(address);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div 
        className="absolute inset-0 bg-black/50"
        onClick={onClose}
      />
      
      {/* Modal */}
      <div className="relative bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] m-4 flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <h2 className="text-xl font-bold">
            Select {type === 'billing' ? 'Billing' : 'Shipping'} Address
          </h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Search */}
        <div className="p-4 border-b">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              placeholder="Search by name, address, or city..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
        </div>

        {/* Address List */}
        <div className="flex-1 overflow-y-auto p-4">
          {filteredAddresses.length === 0 ? (
            <div className="text-center py-12 text-gray-500">
              <MapPin className="w-12 h-12 mx-auto mb-3 text-gray-300" />
              <p>No addresses found</p>
            </div>
          ) : (
            <div className="space-y-3">
              {filteredAddresses.map((address) => (
                <div
                  key={address.id}
                  onClick={() => handleSelect(address)}
                  className={`relative border-2 rounded-lg p-4 cursor-pointer transition-all ${
                    selectedAddressId === address.id
                      ? 'border-primary bg-primary/5'
                      : 'border-gray-200 hover:border-primary/50'
                  }`}
                >
                  {selectedAddressId === address.id && (
                    <div className="absolute top-4 right-4 w-6 h-6 bg-primary rounded-full flex items-center justify-center">
                      <Check className="w-4 h-4 text-white" />
                    </div>
                  )}
                  
                  <div className="pr-10">
                    {/* Label */}
                    <div className="flex items-center gap-2 mb-2">
                      <p className="font-semibold text-base">{address.label}</p>
                      {address.is_default && (
                        <span className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded">
                          Default
                        </span>
                      )}
                    </div>
                    
                    {/* Name & Phone */}
                    <p className="text-sm font-medium text-gray-900">
                      {address.first_name} {address.last_name}
                    </p>
                    {address.phone && (
                      <p className="text-sm text-gray-600">{address.phone}</p>
                    )}
                    
                    {/* Company */}
                    {address.company && (
                      <p className="text-sm text-gray-600">{address.company}</p>
                    )}
                    
                    {/* Address */}
                    <p className="text-sm text-gray-600 mt-2">
                      {address.address_1}
                      {address.address_2 && `, ${address.address_2}`}
                    </p>
                    <p className="text-sm text-gray-600">
                      {address.city}, {address.state} {address.postcode}
                    </p>
                    <p className="text-sm text-gray-600">{address.country}</p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 border-t bg-gray-50">
          <Button
            variant="outline"
            onClick={onClose}
            className="w-full"
          >
            Cancel
          </Button>
        </div>
      </div>
    </div>
  );
}
