import React, { useState, useEffect } from "react";
import { X, MapPin, Plus, CheckCircle } from "lucide-react";
import {
  CustomerAddress,
  customerService,
} from "../../src/services/customer.service";

interface AddressSelectionModalProps {
  isOpen: boolean;
  customerId: number | null;
  onClose: () => void;
  onSelect: (address: CustomerAddress) => void;
  onCreateNew: () => void;
}

const AddressSelectionModal: React.FC<AddressSelectionModalProps> = ({
  isOpen,
  customerId,
  onClose,
  onSelect,
  onCreateNew,
}) => {
  const [addresses, setAddresses] = useState<CustomerAddress[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedAddressId, setSelectedAddressId] = useState<number | null>(
    null
  );

  useEffect(() => {
    if (isOpen && customerId) {
      loadAddresses();
    } else if (isOpen && !customerId) {
      console.warn("AddressSelectionModal: customerId não fornecido");
      setAddresses([]);
    }
  }, [isOpen, customerId]);

  const loadAddresses = async () => {
    if (!customerId) {
      console.warn(
        "AddressSelectionModal: customerId é obrigatório para carregar endereços"
      );
      setAddresses([]);
      return;
    }

    setIsLoading(true);
    try {
      console.log(
        "AddressSelectionModal: Carregando endereços para customerId:",
        customerId
      );
      const customerAddresses = await customerService.getCustomerAddresses(
        customerId
      );
      console.log(
        "AddressSelectionModal: Endereços carregados:",
        customerAddresses
      );
      console.log(
        "AddressSelectionModal: Quantidade de endereços:",
        customerAddresses.length
      );

      if (!Array.isArray(customerAddresses)) {
        console.error(
          "AddressSelectionModal: Resposta da API não é um array:",
          customerAddresses
        );
        setAddresses([]);
        return;
      }

      setAddresses(customerAddresses);
    } catch (error) {
      console.error(
        "AddressSelectionModal: Erro ao carregar endereços:",
        error
      );
      setAddresses([]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleSelect = () => {
    if (selectedAddressId) {
      const address = addresses.find(
        (a) =>
          a.id === selectedAddressId ||
          a.idAddress === selectedAddressId ||
          a.addressId === selectedAddressId
      );
      if (address) {
        onSelect(address);
        onClose();
      }
    }
  };

  const formatAddress = (address: CustomerAddress) => {
    const parts = [];
    const street = address.address || address.street || "";
    const number = address.number || address.numberAddress || "";
    const complement = address.complement || "";

    if (street) parts.push(street);
    if (number) parts.push(number);
    if (complement) parts.push(complement);
    return parts.join(", ");
  };

  const getAddressId = (address: CustomerAddress): number | null => {
    return address.id || address.idAddress || address.addressId || null;
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
      <div className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden">
        {/* Header */}
        <div className="p-6 bg-[#002147] text-white rounded-t-3xl relative overflow-hidden flex-shrink-0">
          <div className="relative z-10 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-orange-500/20 rounded-2xl flex items-center justify-center">
                <MapPin className="w-6 h-6 text-orange-400" />
              </div>
              <div>
                <h3 className="text-xl font-black">
                  Selecionar endereço de entrega
                </h3>
                <p className="text-xs text-orange-400 font-bold uppercase tracking-wider mt-0.5">
                  {addresses.length} endereço{addresses.length !== 1 ? "s" : ""}{" "}
                  encontrado{addresses.length !== 1 ? "s" : ""}
                </p>
              </div>
            </div>
            <button
              onClick={onClose}
              className="w-10 h-10 flex items-center justify-center rounded-xl hover:bg-white/10 transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
          <div className="absolute right-[-10%] top-[-10%] w-32 h-32 bg-orange-400/10 rounded-full blur-2xl"></div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-hidden flex flex-col p-6">
          {isLoading ? (
            <div className="flex-1 flex items-center justify-center">
              <div className="w-12 h-12 border-4 border-[#002147] border-t-transparent rounded-full animate-spin"></div>
            </div>
          ) : addresses.length === 0 ? (
            <div className="flex-1 flex flex-col items-center justify-center">
              <div className="w-20 h-20 bg-slate-100 rounded-full flex items-center justify-center mb-4">
                <MapPin className="w-10 h-10 text-slate-400" />
              </div>
              <p className="text-lg font-bold text-slate-600 mb-2">
                Sem endereços cadastrados
              </p>
              <p className="text-sm text-slate-500 text-center mb-6">
                Este cliente não possui endereços cadastrados. Clique no botão
                abaixo para cadastrar um novo endereço.
              </p>
              <button
                onClick={() => {
                  onClose();
                  onCreateNew();
                }}
                className="flex items-center gap-2 bg-[#002147] text-white px-6 py-3 rounded-xl font-black uppercase text-xs tracking-widest hover:bg-[#001a36] transition-all shadow-lg"
              >
                <Plus className="w-4 h-4" />
                Cadastrar Novo Endereço
              </button>
            </div>
          ) : (
            <>
              <div className="mb-4 flex justify-end">
                <button
                  onClick={() => {
                    onClose();
                    onCreateNew();
                  }}
                  className="flex items-center gap-2 bg-white border-2 border-[#002147] text-[#002147] px-4 py-2 rounded-xl font-bold text-xs hover:bg-[#002147] hover:text-white transition-all"
                >
                  <Plus className="w-4 h-4" />
                  Novo Endereço
                </button>
              </div>

              <div
                className="flex-1 overflow-y-auto space-y-3 pr-2"
                style={{
                  scrollbarWidth: "thin",
                  scrollbarColor: "#cbd5e1 #f1f5f9",
                }}
              >
                {addresses.map((address) => {
                  const addressId = getAddressId(address);
                  const isSelected = selectedAddressId === addressId;
                  return (
                    <div
                      key={addressId || Math.random()}
                      onClick={() => setSelectedAddressId(addressId)}
                      className={`p-4 rounded-2xl border-2 transition-all cursor-pointer ${
                        isSelected
                          ? "bg-orange-50 border-orange-500"
                          : "bg-slate-50 border-slate-200 hover:border-orange-300"
                      }`}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <h4 className="font-black text-slate-800">
                              {address.addressType || "Endereço"}
                            </h4>
                            {address.isPrimary && (
                              <span className="px-2 py-0.5 bg-green-100 text-green-700 rounded-full text-[10px] font-black uppercase">
                                Principal
                              </span>
                            )}
                          </div>
                          <p className="text-sm font-bold text-slate-700 mb-1">
                            {formatAddress(address)}
                          </p>
                          <p className="text-xs text-slate-500">
                            {(address.neighborhood || address.neighbourhood) &&
                              `${
                                address.neighborhood || address.neighbourhood
                              } - `}
                            {address.city && `${address.city}`}
                            {address.state && `/${address.state}`}
                          </p>
                          {address.zipCode && (
                            <p className="text-xs text-slate-500 mt-1">
                              CEP: {address.zipCode}
                            </p>
                          )}
                        </div>
                        {isSelected && (
                          <div className="ml-4">
                            <CheckCircle className="w-6 h-6 text-orange-500" />
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          )}
        </div>

        {/* Footer */}
        {addresses.length > 0 && (
          <div className="p-6 border-t border-slate-200 flex-shrink-0 flex items-center justify-end gap-3">
            <button
              onClick={onClose}
              className="px-6 py-3 rounded-xl font-bold text-slate-700 hover:bg-slate-100 transition-colors"
            >
              Cancelar
            </button>
            <button
              onClick={handleSelect}
              disabled={selectedAddressId === null}
              className="px-6 py-3 rounded-xl font-black bg-[#002147] text-white hover:bg-[#001a36] transition-all shadow-lg shadow-[#002147]/20 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Selecionar
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default AddressSelectionModal;
