import React, { useState, Fragment } from 'react';
import { useNavigate } from 'react-router-dom';
import { Menu, Transition } from '@headlessui/react';
import { useWallet } from '../context/WalletContext';
import { useTranslation } from 'react-i18next';

const WalletsPage = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { userSessionWalletList, createNewWallet, addWalletToCurrentSession, deleteWallet, sessionLogin, activeWallet, switchWallet } = useWallet();
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showConnectModal, setShowConnectModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [walletToDelete, setWalletToDelete] = useState(null);
  const [mnemonic, setMnemonic] = useState('');
  const [password, setPassword] = useState('');
  const [generatedMnemonic, setGeneratedMnemonic] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  
  const storedPassword = sessionStorage.getItem(`password_${sessionLogin}`) || '';

  const handleGenerateNew = async () => {
    setError('');
    setLoading(true);

    try {
      // Проверяем, что введён пароль
      if (!password) {
        setError('Введите пароль');
        setLoading(false);
        return;
      }

      // Проверяем, что пароль совпадает с паролем текущей сессии
      if (password !== storedPassword) {
        setError('Неверный пароль. Введите пароль от текущей сессии.');
        setLoading(false);
        return;
      }

      const result = await createNewWallet();
      if (result.success && result.data.data) {
        setGeneratedMnemonic(result.data.data.mnemonic);
      } else {
        setError('Не удалось создать кошелёк');
      }
    } catch (err) {
      setError(err.message || 'Ошибка создания кошелька');
    } finally {
      setLoading(false);
    }
  };

  const handleConnectWallet = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      // Проверяем, что введён пароль
      if (!password) {
        setError('Введите пароль');
        setLoading(false);
        return;
      }

      // Проверяем, что пароль совпадает с паролем текущей сессии
      if (password !== storedPassword) {
        setError('Неверный пароль. Введите пароль от текущей сессии.');
        setLoading(false);
        return;
      }
      
      const result = await addWalletToCurrentSession(mnemonic.trim(), password, true);
      if (result.success) {
        setShowConnectModal(false);
        setMnemonic('');
        setPassword('');
        navigate('/');
      } else {
        setError(result.error || 'Не удалось импортировать кошелёк');
      }
    } catch (err) {
      setError(err.message || 'Ошибка импорта кошелька');
    } finally {
      setLoading(false);
    }
  };

  const handleUseGeneratedWallet = async () => {
    setError('');
    setLoading(true);

    try {
      const effectivePassword = password || storedPassword;
      if (!effectivePassword) {
        setError('Password required');
        setLoading(false);
        return;
      }
      
      const result = await addWalletToCurrentSession(generatedMnemonic.trim(), effectivePassword);
      if (result.success) {
        setShowCreateModal(false);
        setGeneratedMnemonic('');
        setPassword('');
        navigate('/');
      } else {
        setError(result.error || 'Login failed');
      }
    } catch (err) {
      setError(err.message || 'Connection failed');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteWallet = async () => {
    if (!walletToDelete) return;
    
    setError('');
    setLoading(true);

    try {
      const result = await deleteWallet(walletToDelete.wallet.mnemonic);
      if (result.success) {
        setShowDeleteModal(false);
        setWalletToDelete(null);
        if (userSessionWalletList.length === 1) {
          navigate('/login');
        }
      } else {
        setError(result.error || 'Delete failed');
      }
    } catch (err) {
      setError(err.message || 'Delete failed');
    } finally {
      setLoading(false);
    }
  };

  const openDeleteModal = (wallet) => {
    setWalletToDelete(wallet);
    setShowDeleteModal(true);
    setError('');
  };

  // Обработчики для нижней навигации
  const handleNavigation = (page) => {
    switch(page) {
      case 'home':
        navigate('/');
        break;
      case 'swap':
        navigate('/swap');
        break;
      case 'earn':
        navigate('/earn');
        break;
      case 'settings':
        navigate('/settings');
        break;
      default:
        break;
    }
  };

  return (
    <div className="min-h-screen bg-[#1b1b1c]">
      {/* Header */}
      <div className="px-4 py-4 bg-[#1b1b1c] mobile-safe-area">
        <div className="max-w-md mx-auto container-mobile">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center space-x-2">
              {/* Wallet Switcher */}
              {userSessionWalletList.length > 1 ? (
                <Menu as="div" className="relative">
                  <Menu.Button className="flex items-center space-x-2 text-white font-medium hover:text-gray-300 transition-colors">
                    <span>
                      {activeWallet && userSessionWalletList.find(item => 
                        item.wallet?.mnemonic === activeWallet?.mnemonic
                      )?.walletName || 'Мультисетевой кошелёк'}
                    </span>
                    <svg className="w-4 h-4 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clipRule="evenodd" />
                    </svg>
                  </Menu.Button>

                  <Transition
                    as={Fragment}
                    enter="transition ease-out duration-100"
                    enterFrom="transform opacity-0 scale-95"
                    enterTo="transform opacity-100 scale-100"
                    leave="transition ease-in duration-75"
                    leaveFrom="transform opacity-100 scale-100"
                    leaveTo="transform opacity-0 scale-95"
                  >
                    <Menu.Items className="absolute left-0 mt-2 w-56 origin-top-left rounded-lg bg-[#1b1b1c] shadow-xl ring-1 ring-black ring-opacity-5 focus:outline-none border border-gray-800 z-50">
                      <div className="py-1">
                        {userSessionWalletList.map((item, index) => {
                          const isActive = activeWallet?.mnemonic === item.wallet?.mnemonic;
                          return (
                            <Menu.Item key={index}>
                              {({ active }) => (
                                <button
                                  onClick={async () => {
                                    if (!isActive && item.wallet?.mnemonic) {
                                      await switchWallet(item.wallet.mnemonic, index);
                                    }
                                  }}
                                  className={`${
                                    active ? 'bg-gray-700' : ''
                                  } ${
                                    isActive ? 'bg-gray-700' : ''
                                  } group flex w-full items-center justify-between px-4 py-3 text-sm text-gray-300`}
                                >
                                  <div className="flex items-center space-x-3">
                                    <div className="w-8 h-8 rounded-full bg-gradient-to-br from-green-500 to-blue-600 flex items-center justify-center text-white font-bold text-xs">
                                      {(item.walletName || `Wallet ${index + 1}`).charAt(0)}
                                    </div>
                                    <div className="text-left">
                                      <div className="font-medium">{item.walletName || `Wallet ${index + 1}`}</div>
                                      <div className="text-xs text-gray-500">
                                        {item.wallet?.tokens?.length || 0} tokens
                                      </div>
                                    </div>
                                  </div>
                                  {isActive && (
                                    <svg className="w-5 h-5 text-blue-500" fill="currentColor" viewBox="0 0 20 20">
                                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                                    </svg>
                                  )}
                                </button>
                              )}
                            </Menu.Item>
                          );
                        })}
                      </div>
                    </Menu.Items>
                  </Transition>
                </Menu>
              ) : (
                <span className="text-white font-medium">
                  {activeWallet && userSessionWalletList.find(item => 
                    item.wallet?.mnemonic === activeWallet?.mnemonic
                  )?.walletName || 'Мультисетевой кошелёк'}
                </span>
              )}
              <button className="text-xs bg-gray-700 text-gray-300 px-2 py-1 rounded">
                {userSessionWalletList.find(item => 
                  item.wallet?.mnemonic === activeWallet?.mnemonic
                )?.wallet?.tokens?.length || 0} tokens
              </button>
            </div>

            <button 
              onClick={() => navigate('/settings')}
              className="p-2 rounded-lg bg-gray-700/50 hover:bg-gray-600/50 transition-colors"
            >
              <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
              </svg>
            </button>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="px-4 mobile-safe-area pb-24">
        <div className="max-w-md mx-auto container-mobile space-y-6">
        {/* Заголовок */}
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-2xl font-bold text-white mb-1">{t('Manage wallets')}</h1>
            <p className="text-sm text-gray-400">Управление вашими кошельками</p>
          </div>
        </div>

        {/* Кнопки действий */}
        <div className="grid grid-cols-2 gap-3 mb-6">
          <button
            onClick={() => setShowCreateModal(true)}
            className="bg-[#48ff91] hover:bg-[#3de080] text-black font-medium py-4 px-6 rounded-xl transition-all duration-200 flex items-center justify-center space-x-2"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
            <span>Создать кошелёк</span>
          </button>
          <button
            onClick={() => setShowConnectModal(true)}
            className="bg-[#1a1b1f] hover:bg-[#2a2b2f] text-white font-medium py-4 px-6 rounded-xl border border-gray-700 hover:border-gray-600 transition-all duration-200 flex items-center justify-center space-x-2"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
            </svg>
            <span>Импортировать</span>
          </button>
        </div>

        {/* Список кошельков */}
        <div className="space-y-3">
          {userSessionWalletList.map((item, index) => {
            const totalBalance = item.wallet?.tokens
              ?.filter(token => token.show)
              ?.reduce((sum, token) => {
                const balance = parseFloat(token.balance) || 0;
                const price = parseFloat(token.tokenInfo?.price) || 0;
                return sum + (balance * price);
              }, 0) || 0;

            const visibleTokens = item.wallet?.tokens?.filter(token => token.show) || [];

            return (
              <div
                key={index}
                className="bg-[#1a1b1f] rounded-xl p-4 hover:bg-[#2a2b2f] transition-all duration-200 relative group cursor-pointer"
                onClick={() => navigate('/')}
              >
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center space-x-3">
                    <div className="w-12 h-12 rounded-full bg-gradient-to-br from-[#48ff91] to-[#00d4ff] flex items-center justify-center text-black font-bold text-lg">
                      {(item.walletName || `W${index + 1}`).charAt(0).toUpperCase()}
                    </div>
                    <div>
                      <h3 className="text-white font-semibold">
                        {item.walletName || `Кошелёк ${index + 1}`}
                      </h3>
                      <p className="text-xs text-gray-400">
                        {visibleTokens.length} {visibleTokens.length === 1 ? 'токен' : 'токенов'}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <div className="text-right">
                      <div className="text-white font-semibold">
                        ${totalBalance.toFixed(2)}
                      </div>
                      <div className="text-xs text-gray-400">Баланс</div>
                    </div>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        openDeleteModal(item);
                      }}
                      className="opacity-0 group-hover:opacity-100 transition-opacity ml-2 p-2 rounded-lg bg-red-500/10 hover:bg-red-500/20 text-red-500"
                      title="Удалить кошелёк"
                    >
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                </div>

                {/* Превью токенов */}
                {visibleTokens.length > 0 && (
                  <div className="flex items-center space-x-2 pt-3 border-t border-gray-700/50">
                    <span className="text-xs text-gray-400">Токены:</span>
                    <div className="flex -space-x-2">
                      {visibleTokens.slice(0, 6).map((token, tokenIndex) => (
                        <div
                          key={tokenIndex}
                          className="w-6 h-6 rounded-full bg-gray-800 border-2 border-[#1a1b1f] flex items-center justify-center text-[10px] font-bold text-white"
                          title={token.tokenInfo?.symbol}
                        >
                          {token.tokenInfo?.symbol?.charAt(0)}
                        </div>
                      ))}
                    </div>
                    {visibleTokens.length > 6 && (
                      <span className="text-xs text-gray-500">
                        +{visibleTokens.length - 6}
                      </span>
                    )}
                  </div>
                )}
              </div>
            );
          })}

          {userSessionWalletList.length === 0 && (
            <div className="bg-[#1a1b1f] rounded-xl p-12 text-center">
              <div className="w-20 h-20 mx-auto mb-4 rounded-full bg-gray-800 flex items-center justify-center">
                <svg className="w-10 h-10 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                </svg>
              </div>
              <p className="text-gray-400 mb-2 text-lg font-medium">Нет кошельков</p>
              <p className="text-sm text-gray-500">Создайте новый кошелёк или импортируйте существующий</p>
            </div>
          )}
        </div>
        </div>
      </div>

      {/* Bottom Navigation */}
      <div className="fixed bottom-0 left-0 right-0 bg-[#1b1b1c] mobile-safe-area">
        <div className="max-w-md mx-auto px-4 py-2 border-t border-gray-800">
          <div className="flex justify-around">
            <button 
              onClick={() => handleNavigation('home')}
              className="flex flex-col items-center py-2 hover:bg-gray-700 rounded transition-colors touch-target"
              title="Главная страница"
            >
              <svg className="w-6 h-6 text-gray-400 mb-1" fill="none" width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path d="M22.61 11.38C22.45 11.7 22.14 11.86 21.82 11.86C21.61 11.86 21.41 11.79 21.24 11.64L20.92 11.37V19.66C20.92 20.91 19.9 21.92 18.65 21.92H14.58C13.83 21.92 13.22 21.31 13.22 20.56V15.8C13.22 15.68 13.12 15.58 12.99 15.58H10.73C10.6 15.58 10.5 15.68 10.5 15.8V20.56C10.5 21.31 9.89997 21.92 9.14997 21.92H5.06997C3.81997 21.92 2.79997 20.91 2.79997 19.66V11.37L2.47997 11.64C2.30997 11.79 2.09997 11.86 1.88997 11.86C1.58997 11.86 1.28997 11.7 1.11997 11.41C0.889973 11.01 1.00997 10.51 1.35997 10.22L10.7 2.42C11.04 2.14 11.45 2 11.86 2C12.27 2 12.69 2.14 13.02 2.42L18.19 6.75V5.17C18.19 4.67 18.61 4.26 19.1 4.26H20.01C20.51 4.26 20.92 4.67 20.92 5.17V9.02L22.37 10.23C22.7 10.51 22.83 10.99 22.61 11.38Z" fill="currentColor"></path>
              </svg>
              <span className="text-xs text-gray-400">Главная</span>
            </button>
            <button 
              onClick={() => handleNavigation('swap')}
              className="flex flex-col items-center py-2 hover:bg-gray-700 rounded transition-colors touch-target"
              title="Обмен криптовалют"
            >
               <svg className="w-6 h-6 text-gray-400 mb-1" fill="none" width="25" height="24" viewBox="0 0 25 24" xmlns="http://www.w3.org/2000/svg">
                 <path d="M22.7877 5.215C22.1977 5.025 21.5677 5.355 21.3777 5.945L20.7177 8.025C20.6277 7.835 20.5377 7.655 20.4377 7.455C18.7777 4.475 15.6277 2.625 12.2277 2.625C8.82771 2.625 5.67771 4.475 4.01771 7.455C3.71771 7.995 3.90771 8.685 4.45771 8.985C4.99771 9.285 5.68771 9.095 5.98771 8.545C7.24771 6.285 9.63771 4.875 12.2277 4.875C14.8177 4.875 17.2077 6.285 18.4577 8.545C18.5677 8.745 18.6577 8.935 18.7477 9.125L16.5677 8.425C15.9777 8.235 15.3477 8.565 15.1577 9.155C14.9677 9.745 15.2977 10.375 15.8877 10.565L20.6077 12.065C20.7177 12.105 20.8377 12.115 20.9477 12.115C21.4277 12.115 21.8677 11.815 22.0177 11.335L23.5177 6.615C23.7077 6.025 23.3777 5.395 22.7877 5.205V5.215Z" fill="currentColor"></path>
                 <path d="M19.9875 15.015C19.4475 14.715 18.7575 14.905 18.4575 15.455C17.1975 17.715 14.8075 19.125 12.2175 19.125C9.62752 19.125 7.23752 17.715 5.98752 15.455C5.92752 15.345 5.87752 15.235 5.82752 15.135L8.09752 15.865C8.68752 16.055 9.31752 15.725 9.50752 15.135C9.69752 14.545 9.36752 13.915 8.77752 13.725L4.05752 12.225C3.46752 12.035 2.83752 12.365 2.64752 12.955L1.14752 17.655C0.957522 18.245 1.28752 18.875 1.87752 19.065C1.98752 19.105 2.10752 19.115 2.21752 19.115C2.69752 19.115 3.13752 18.815 3.28752 18.335L3.91752 16.355C3.94752 16.415 3.97752 16.475 4.00752 16.545C5.65752 19.525 8.80752 21.375 12.2075 21.375C15.6075 21.375 18.7575 19.525 20.4075 16.545C20.7075 16.005 20.5175 15.315 19.9675 15.015H19.9875Z" fill="currentColor"></path>
               </svg>
              <span className="text-xs text-gray-400">Своп</span>
            </button>
            <button 
              onClick={() => handleNavigation('earn')}
              className="flex flex-col items-center py-2 hover:bg-gray-700 rounded transition-colors touch-target"
              title="Заработок"
            >
              <svg className="w-6 h-6 text-gray-400 mb-1" fill="none" width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path d="M21.9216 5.51412C21.8916 5.28556 21.7214 5.11662 21.4911 5.08681C21.1207 5.04706 20.51 4.98745 19.7691 4.98745C17.937 4.98745 15.3139 5.31538 13.6519 6.9749C13.0012 7.62082 12.5607 8.41579 12.2503 9.25052C12.0501 7.75993 11.5294 6.14017 10.3681 4.98745C8.70614 3.33787 6.08306 3 4.25091 3C3.51004 3 2.89932 3.04968 2.52889 3.09936C2.29862 3.12918 2.12842 3.29812 2.09838 3.52667C1.94821 4.79864 1.65786 8.99216 4.00061 11.3075C5.66256 12.9571 8.28564 13.295 10.1178 13.295C10.3981 13.295 10.6484 13.295 10.8787 13.2751V20.887C10.8787 21.5031 11.3793 22 12 22C12.6207 22 13.1213 21.5031 13.1213 20.887V15.2626C13.3616 15.2725 13.6119 15.2824 13.8822 15.2824C15.7144 15.2824 18.3374 14.9545 19.9994 13.295C22.3421 10.9697 22.0518 6.78609 21.9016 5.51412H21.9216ZM5.59248 9.7275C4.60132 8.74371 4.25091 6.90534 4.25091 5.23588C5.44231 5.23588 7.61485 5.40481 8.77622 6.56747C9.76738 7.55125 10.1178 9.38965 10.1178 11.0591C8.92639 11.0591 6.75384 10.8902 5.59248 9.7275ZM18.4275 11.7149C17.2662 12.8677 15.0936 13.0466 13.9022 13.0466C13.9022 11.3672 14.2526 9.5387 15.2438 8.55491C16.4052 7.40219 18.5777 7.22333 19.7691 7.22333C19.7691 8.90272 19.4187 10.7312 18.4275 11.7149Z" fill="currentColor"></path>
              </svg>
              <span className="text-xs text-gray-400">Earn</span>
            </button>
            <button 
              onClick={() => handleNavigation('settings')}
              className="flex flex-col items-center py-2 hover:bg-gray-700 rounded transition-colors touch-target"
              title="Настройки"
            >
              <svg className="w-6 h-6 text-[#48ff91] mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
              </svg>
              <span className="text-xs text-[#48ff91]">Настройки</span>
            </button>
          </div>
        </div>
      </div>

      {/* Create Wallet Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <div className="bg-[#1a1b1f] rounded-2xl max-w-md w-full p-6 shadow-2xl border border-gray-800">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-xl font-bold text-white">Создать кошелёк</h3>
              <button
                onClick={() => {
                  setShowCreateModal(false);
                  setGeneratedMnemonic('');
                  setError('');
                }}
                className="text-gray-400 hover:text-white transition-colors"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {error && (
              <div className="mb-4 p-3 bg-red-500/10 border border-red-500/30 rounded-xl text-red-400 text-sm">
                {error}
              </div>
            )}

            {!generatedMnemonic ? (
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-300 mb-2">
                    Пароль текущей сессии
                  </label>
                  <input
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="w-full bg-[#0a0b0d] border border-gray-700 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-[#48ff91] transition-colors"
                    placeholder="Введите пароль от вашей сессии"
                    required
                  />
                  <p className="text-xs text-gray-400 mt-1">
                    Используйте тот же пароль, с которым вы вошли в систему
                  </p>
                </div>

                <button
                  onClick={handleGenerateNew}
                  disabled={loading || !password}
                  className="w-full bg-[#48ff91] hover:bg-[#3de080] text-black font-semibold py-3 px-4 rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {loading ? 'Генерация...' : 'Сгенерировать кошелёк'}
                </button>
              </div>
            ) : (
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-300 mb-2">
                    Ваша seed-фраза
                  </label>
                  <div className="bg-[#0a0b0d] border border-gray-700 rounded-xl p-4 mb-3">
                    <p className="text-white text-sm font-mono break-words leading-relaxed">
                      {generatedMnemonic}
                    </p>
                  </div>
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(generatedMnemonic);
                      alert('Скопировано в буфер обмена!');
                    }}
                    className="w-full bg-[#1a1b1f] hover:bg-[#2a2b2f] text-white font-medium py-2.5 px-4 rounded-xl border border-gray-700 hover:border-gray-600 transition-colors flex items-center justify-center space-x-2"
                  >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                    </svg>
                    <span>Копировать</span>
                  </button>
                </div>

                <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-xl p-3">
                  <p className="text-yellow-400 text-sm flex items-start space-x-2">
                    <svg className="w-5 h-5 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                    </svg>
                    <span>Сохраните эту фразу в надёжном месте! Она понадобится для восстановления доступа к кошельку.</span>
                  </p>
                </div>

                <button
                  onClick={handleUseGeneratedWallet}
                  disabled={loading}
                  className="w-full bg-[#48ff91] hover:bg-[#3de080] text-black font-semibold py-3 px-4 rounded-xl transition-colors disabled:opacity-50"
                >
                  {loading ? 'Добавление...' : 'Добавить кошелёк'}
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Connect Wallet Modal */}
      {showConnectModal && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <div className="bg-[#1a1b1f] rounded-2xl max-w-md w-full p-6 shadow-2xl border border-gray-800">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-xl font-bold text-white">Импортировать кошелёк</h3>
              <button
                onClick={() => {
                  setShowConnectModal(false);
                  setMnemonic('');
                  setError('');
                }}
                className="text-gray-400 hover:text-white transition-colors"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {error && (
              <div className="mb-4 p-3 bg-red-500/10 border border-red-500/30 rounded-xl text-red-400 text-sm">
                {error}
              </div>
            )}

            <form onSubmit={handleConnectWallet} className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Seed-фраза (12 или 24 слова)
                </label>
                <textarea
                  value={mnemonic}
                  onChange={(e) => setMnemonic(e.target.value)}
                  className="w-full bg-[#0a0b0d] border border-gray-700 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-[#48ff91] transition-colors h-28 resize-none font-mono text-sm"
                  placeholder="word1 word2 word3 ..."
                  required
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-300 mb-2">
                  Пароль текущей сессии
                </label>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full bg-[#0a0b0d] border border-gray-700 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-[#48ff91] transition-colors"
                  placeholder="Введите пароль от вашей сессии"
                  required
                />
                <p className="text-xs text-gray-400 mt-1">
                  Используйте тот же пароль, с которым вы вошли в систему
                </p>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full bg-[#48ff91] hover:bg-[#3de080] text-black font-semibold py-3 px-4 rounded-xl transition-colors disabled:opacity-50"
              >
                {loading ? 'Подключение...' : 'Импортировать кошелёк'}
              </button>
            </form>
          </div>
        </div>
      )}

      {/* Delete Wallet Confirmation Modal */}
      {showDeleteModal && walletToDelete && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <div className="bg-[#1a1b1f] rounded-2xl max-w-md w-full p-6 shadow-2xl border border-gray-800">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-xl font-bold text-white">Удалить кошелёк</h3>
              <button
                onClick={() => {
                  setShowDeleteModal(false);
                  setWalletToDelete(null);
                  setError('');
                }}
                className="text-gray-400 hover:text-white transition-colors"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {error && (
              <div className="mb-4 p-3 bg-red-500/10 border border-red-500/30 rounded-xl text-red-400 text-sm">
                {error}
              </div>
            )}

            <div className="mb-6">
              <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-red-500/10 flex items-center justify-center">
                <svg className="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
              </div>
              <p className="text-gray-300 mb-4 text-center">
                Вы уверены, что хотите удалить <strong className="text-white">{walletToDelete.walletName || 'этот кошелёк'}</strong>?
              </p>
              <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-4">
                <p className="text-red-400 text-sm">
                  <span className="font-semibold">Внимание!</span> Это действие нельзя отменить. Убедитесь, что у вас сохранена seed-фраза для восстановления доступа!
                </p>
              </div>
            </div>

            <div className="flex space-x-3">
              <button
                onClick={() => {
                  setShowDeleteModal(false);
                  setWalletToDelete(null);
                  setError('');
                }}
                className="flex-1 bg-[#1a1b1f] hover:bg-[#2a2b2f] text-white font-medium py-3 px-4 rounded-xl border border-gray-700 hover:border-gray-600 transition-colors"
                disabled={loading}
              >
                Отмена
              </button>
              <button
                onClick={handleDeleteWallet}
                disabled={loading}
                className="flex-1 bg-red-600 hover:bg-red-700 text-white py-3 px-4 rounded-xl font-semibold transition-colors disabled:opacity-50"
              >
                {loading ? 'Удаление...' : 'Удалить'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default WalletsPage;
