import React, { useState, useEffect, useCallback } from 'react';
import { listAddresses, deleteAddress, setDefaultAddress } from '../core/checkout-api';
import type { SavedAddress } from '../core/checkout-api';
import type { SavedAddressStepProps } from '../core/types';

// ─── Label icons ──────────────────────────────────────────────────────────────

const HomeIcon = () => (
  <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 9.5L12 3l9 6.5V20a1 1 0 01-1 1H4a1 1 0 01-1-1V9.5z" />
    <path d="M9 21V12h6v9" />
  </svg>
);

const WorkIcon = () => (
  <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <rect x="2" y="7" width="20" height="14" rx="2" />
    <path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2" />
  </svg>
);

const PinIcon = () => (
  <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M12 2C8.134 2 5 5.134 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7z" />
    <circle cx="12" cy="9" r="2.5" />
  </svg>
);

function LabelIcon({ label }: { label: string }) {
  if (label === 'home') return <HomeIcon />;
  if (label === 'work') return <WorkIcon />;
  return <PinIcon />;
}

function formatAddressLabel(address: SavedAddress): string {
  const custom = address.label_text?.trim();
  if (address.label === 'other' && custom) return custom;
  return address.label.charAt(0).toUpperCase() + address.label.slice(1);
}

// ─── Address card ─────────────────────────────────────────────────────────────

interface AddressCardProps {
  address: SavedAddress;
  onUse: () => void;
  onDelete: () => void;
  onSetDefault: () => void;
  deleting: boolean;
}

function AddressCard({ address, onUse, onDelete, onSetDefault, deleting }: AddressCardProps) {
  const parts = [
    address.flat_number,
    address.building_name,
    address.street_name,
    address.locality,
    address.district,
    address.state,
    address.pincode,
  ].filter(Boolean);
  const line1 = [address.flat_number, address.building_name, address.street_name].filter(Boolean).join(', ');
  const line2 = [address.locality, address.district].filter(Boolean).join(', ');
  const line3 = [address.state, address.pincode].filter(Boolean).join(' – ');
  const summary = parts.length > 0 ? undefined : address.locality || address.district || address.state;

  return (
    <div className={`qr-addr-card${address.is_default ? ' qr-addr-card--default' : ''}`}>
      <div className="qr-addr-card__header">
        <div className="qr-addr-card__label-icon">
          <LabelIcon label={address.label} />
        </div>
        <span className="qr-addr-card__label">
          {formatAddressLabel(address)}
        </span>
        {address.is_default && (
          <span className="qr-addr-card__default-badge">Default</span>
        )}
        <div className="qr-addr-card__actions">
          {!address.is_default && (
            <button
              type="button"
              className="qr-icon-btn"
              title="Set as default"
              onClick={onSetDefault}
              aria-label="Set as default address"
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
              </svg>
            </button>
          )}
          <button
            type="button"
            className="qr-icon-btn qr-icon-btn--danger"
            title="Delete address"
            onClick={onDelete}
            disabled={deleting}
            aria-label="Delete address"
          >
            {deleting ? (
              <span className="qr-spinner qr-spinner--xs" aria-hidden="true" />
            ) : (
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="3 6 5 6 21 6" />
                <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />
                <path d="M10 11v6M14 11v6" />
                <path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" />
              </svg>
            )}
          </button>
        </div>
      </div>

      <div className="qr-addr-card__body">
        {summary ? (
          <p className="qr-addr-card__line">{summary}</p>
        ) : (
          <>
            {line1 && <p className="qr-addr-card__line">{line1}</p>}
            {line2 && <p className="qr-addr-card__line qr-addr-card__line--muted">{line2}</p>}
            {line3 && <p className="qr-addr-card__line qr-addr-card__line--muted">{line3}</p>}
          </>
        )}
        <div className="qr-addr-card__meta">
          {address.digipin ? (
            <span className="qr-digipin-badge qr-digipin-badge--inline qr-digipin-badge--sm">
              <span className="qr-digipin-badge__label">DigiPin</span>
              <span className="qr-digipin-badge__code">{address.digipin}</span>
            </span>
          ) : (
            <span className="qr-addr-card__pending-pin">Pin confirmation needed</span>
          )}
          {address.saved_at_brand && (
            <span className="qr-addr-card__brand-chip" title={`First saved at ${address.saved_at_brand}`}>
              <svg viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
                <path d="M1 1h4.5l5.5 5.5-4.5 4.5L1 5.5V1zm2 1.5a.75.75 0 100 1.5.75.75 0 000-1.5z" />
              </svg>
              {address.saved_at_brand}
            </span>
          )}
        </div>
      </div>

      <button
        type="button"
        className="qr-btn qr-btn--primary qr-btn--full qr-btn--sm"
        onClick={onUse}
      >
        Deliver here
      </button>
    </div>
  );
}

// ─── Main component ───────────────────────────────────────────────────────────

const SavedAddressStep: React.FC<SavedAddressStepProps> = ({
  sessionToken,
  functionBaseUrl,
  merchantId,
  onSelectAddress,
  onAddNew,
}) => {
  const [addresses, setAddresses] = useState<SavedAddress[]>([]);
  const [loadingList, setLoadingList] = useState(true);
  const [listError, setListError] = useState<string | null>(null);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const config = { functionBaseUrl, merchantId };

  const load = useCallback(async () => {
    setLoadingList(true);
    setListError(null);
    try {
      const list = await listAddresses(config, sessionToken);
      if (list.length === 0) {
        // No saved addresses — go straight to map
        onAddNew();
        return;
      }
      setAddresses(list);
    } catch (err: unknown) {
      setListError(err instanceof Error ? err.message : 'Failed to load addresses.');
    } finally {
      setLoadingList(false);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionToken]);

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

  const handleDelete = useCallback(async (id: string) => {
    setDeletingId(id);
    try {
      await deleteAddress(config, sessionToken, id);
      setAddresses((prev) => {
        const updated = prev.filter((a) => a.id !== id);
        if (updated.length === 0) { onAddNew(); }
        return updated;
      });
    } catch (err: unknown) {
      setListError(err instanceof Error ? err.message : 'Failed to delete address.');
    } finally {
      setDeletingId(null);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionToken, onAddNew]);

  const handleSetDefault = useCallback(async (id: string) => {
    try {
      await setDefaultAddress(config, sessionToken, id);
      setAddresses((prev) => prev.map((a) => ({ ...a, is_default: a.id === id })));
    } catch (err: unknown) {
      setListError(err instanceof Error ? err.message : 'Failed to set default.');
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sessionToken]);

  // ── Loading ──────────────────────────────────────────────────────────────────
  if (loadingList) {
    return (
      <div className="qr-saved-step">
        <div className="qr-saved-step__loading" aria-live="polite">
          <span className="qr-spinner" aria-label="Loading addresses" />
        </div>
      </div>
    );
  }

  // ── Error ────────────────────────────────────────────────────────────────────
  if (listError && addresses.length === 0) {
    return (
      <div className="qr-saved-step">
        <p className="qr-auth-step__error" role="alert">{listError}</p>
        <button type="button" className="qr-btn qr-btn--ghost qr-btn--full" onClick={load}>
          Retry
        </button>
        <button type="button" className="qr-auth-step__skip" onClick={onAddNew}>
          Enter address manually
        </button>
      </div>
    );
  }

  return (
    <div className="qr-saved-step">
      <div className="qr-step-header">
        <div className="qr-step-badge qr-step-badge--saved">
          <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 2C8.134 2 5 5.134 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7z" />
            <circle cx="12" cy="9" r="2.5" />
          </svg>
        </div>
        <div className="qr-step-text">
          <span className="qr-step-title">Saved Addresses</span>
          <span className="qr-step-sub">Pick one or add a new location</span>
        </div>
      </div>

      {listError && (
        <p className="qr-auth-step__error" role="alert">{listError}</p>
      )}

      <div className="qr-saved-step__list">
        {addresses.map((addr) => (
          <AddressCard
            key={addr.id}
            address={addr}
            onUse={() => onSelectAddress(addr)}
            onDelete={() => handleDelete(addr.id)}
            onSetDefault={() => handleSetDefault(addr.id)}
            deleting={deletingId === addr.id}
          />
        ))}
      </div>

      <button
        type="button"
        className="qr-btn qr-btn--ghost qr-btn--full"
        onClick={onAddNew}
      >
        <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 5v14M5 12h14" />
        </svg>
        Add new address
      </button>
    </div>
  );
};

export default SavedAddressStep;
