import { useState, useCallback } from 'react';

interface AddressRow {
  address: string;
  label: string;
}

interface AddressesTabProps {
  addresses: string[];
  addrLabels: Record<string, string>;
  onSetLabel: (kind: string, identifier: string, label: string) => void;
  onDeriveMore: (n: number) => Promise<string[]>;
  loading: boolean;
}

export default function AddressesTab({
  addresses,
  addrLabels,
  onSetLabel,
  onDeriveMore,
  loading,
}: AddressesTabProps) {
  const [editingAddr, setEditingAddr] = useState('');
  const [editingLabel, setEditingLabel] = useState('');

  const showToast = (msg: string) => {
    const t = document.createElement('div');
    t.className = 'toast';
    t.textContent = msg;
    document.body.appendChild(t);
    setTimeout(() => t.remove(), 2000);
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text).then(() => showToast('Address copied!'));
  };

  const startEdit = (addr: string) => {
    setEditingAddr(addr);
    setEditingLabel(addrLabels[addr] || '');
  };

  const saveLabel = async () => {
    if (editingAddr) {
      await onSetLabel('addr', editingAddr, editingLabel);
      setEditingAddr('');
      setEditingLabel('');
    }
  };

  const handleDerive = async () => {
    const newAddrs = await onDeriveMore(5);
    if (newAddrs.length > 0) {
      showToast(`Derived ${newAddrs.length} new addresses`);
    }
  };

  return (
    <div className="tab-content">
      <div className="section">
        <div className="section-header">
          <h3>Addresses ({addresses.length})</h3>
          <button className="btn btn-secondary btn-small" onClick={handleDerive} disabled={loading}>
            Derive 5 More
          </button>
        </div>

        {addresses.length === 0 ? (
          <div className="empty-state">
            <div className="empty-state-icon">◈</div>
            No addresses derived yet
          </div>
        ) : (
          <table className="wallet-table">
            <thead>
              <tr>
                <th>Address</th>
                <th>Label</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {addresses.map(addr => (
                <tr key={addr}>
                  <td className="mono" style={{ fontSize: '12px', maxWidth: '300px', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    <span style={{ cursor: 'pointer' }} onClick={() => copyToClipboard(addr)}>
                      {addr}
                    </span>
                  </td>
                  <td>
                    {editingAddr === addr ? (
                      <input
                        className="label-edit"
                        value={editingLabel}
                        onChange={e => setEditingLabel(e.target.value)}
                        onBlur={saveLabel}
                        onKeyDown={e => { if (e.key === 'Enter') saveLabel(); if (e.key === 'Escape') setEditingAddr(''); }}
                        autoFocus
                      />
                    ) : (
                      <span
                        className="label-tag"
                        onClick={() => startEdit(addr)}
                        title="Click to edit label"
                      >
                        {addrLabels[addr] || '—'}
                      </span>
                    )}
                  </td>
                  <td>
                    <button className="btn-icon btn-small" onClick={() => copyToClipboard(addr)} title="Copy address">
                      ⧉
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}