import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useWalletStore, type Network } from '../store/wallet';
import { HardwareWalletConnect } from '../components/HardwareWalletConnect';
import { LanguageSelector } from '../components/LanguageSelector';
import {
  isHardwareWalletSupported,
  type HardwareWalletAccount,
  type HardwareWallet,
} from '../lib/hardware-wallet';

export default function SettingsPage() {
  const { t } = useTranslation();
  const {
    network,
    rpcEndpoint,
    setNetwork,
    setRpcEndpoint,
    deleteWallet,
  } = useWalletStore();
  const navigate = useNavigate();

  const [customEndpoint, setCustomEndpoint] = useState(rpcEndpoint);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [deleteConfirmText, setDeleteConfirmText] = useState('');
  const [showHardwareConnect, setShowHardwareConnect] = useState(false);
  const [connectedHardwareWallet, setConnectedHardwareWallet] = useState<{
    account: HardwareWalletAccount;
    wallet: HardwareWallet;
  } | null>(null);

  const handleHardwareWalletConnected = (
    account: HardwareWalletAccount,
    wallet: HardwareWallet
  ) => {
    setConnectedHardwareWallet({ account, wallet });
    setShowHardwareConnect(false);
  };

  const handleNetworkChange = (newNetwork: Network) => {
    setNetwork(newNetwork);
    // Update default endpoint based on network
    const defaultEndpoints: Record<Network, string> = {
      mainnet: 'https://rpc.synor.cc',
      testnet: 'https://testnet-rpc.synor.cc',
      devnet: 'http://localhost:16110',
    };
    setRpcEndpoint(defaultEndpoints[newNetwork]);
    setCustomEndpoint(defaultEndpoints[newNetwork]);
  };

  const handleSaveEndpoint = () => {
    setRpcEndpoint(customEndpoint);
  };

  const handleDeleteWallet = () => {
    if (deleteConfirmText === 'DELETE') {
      deleteWallet();
      navigate('/');
    }
  };

  return (
    <div className="max-w-2xl">
      <h1 className="text-2xl font-bold mb-6">Settings</h1>

      {/* Network Selection */}
      <div className="card mb-6">
        <h2 className="text-lg font-semibold mb-4">Network</h2>
        <div className="grid grid-cols-3 gap-3">
          {(['mainnet', 'testnet', 'devnet'] as Network[]).map((net) => (
            <button
              key={net}
              onClick={() => handleNetworkChange(net)}
              className={`p-4 rounded-lg border-2 transition-colors ${
                network === net
                  ? 'border-synor-500 bg-synor-900/30'
                  : 'border-slate-700 hover:border-slate-600'
              }`}
            >
              <div className="flex items-center gap-2 mb-1">
                <span
                  className={`w-2 h-2 rounded-full ${
                    net === 'mainnet'
                      ? 'bg-green-500'
                      : net === 'testnet'
                      ? 'bg-yellow-500'
                      : 'bg-blue-500'
                  }`}
                ></span>
                <span className="font-medium capitalize">{net}</span>
              </div>
              <div className="text-xs text-slate-500">
                {net === 'mainnet' && 'Production network'}
                {net === 'testnet' && 'Test with fake SYNOR'}
                {net === 'devnet' && 'Local development'}
              </div>
            </button>
          ))}
        </div>
        {network === 'mainnet' && (
          <div className="mt-4 p-3 bg-yellow-900/30 border border-yellow-700 rounded-lg text-yellow-300 text-sm">
            Mainnet is not yet launched. Switch to testnet or devnet.
          </div>
        )}
      </div>

      {/* RPC Endpoint */}
      <div className="card mb-6">
        <h2 className="text-lg font-semibold mb-4">RPC Endpoint</h2>
        <div className="flex gap-3">
          <input
            type="text"
            value={customEndpoint}
            onChange={(e) => setCustomEndpoint(e.target.value)}
            className="input flex-1"
            placeholder="http://localhost:16110"
          />
          <button
            onClick={handleSaveEndpoint}
            disabled={customEndpoint === rpcEndpoint}
            className="btn btn-secondary"
          >
            Save
          </button>
        </div>
        <p className="text-xs text-slate-500 mt-2">
          Connect to a custom Synor node
        </p>
      </div>

      {/* Hardware Wallet */}
      <div className="card mb-6">
        <h2 className="text-lg font-semibold mb-4">Hardware Wallet</h2>
        {connectedHardwareWallet ? (
          <div className="space-y-3">
            <div className="flex items-center gap-3 p-3 bg-green-900/30 border border-green-700/50 rounded-lg">
              <div className="w-2 h-2 bg-green-400 rounded-full" />
              <div className="flex-1">
                <div className="text-green-300 text-sm font-medium">
                  {connectedHardwareWallet.wallet.type === 'ledger' ? 'Ledger' : 'Trezor'} Connected
                </div>
                <div className="text-xs text-slate-400 font-mono truncate">
                  {connectedHardwareWallet.account.address}
                </div>
              </div>
            </div>
            <button
              onClick={() => {
                connectedHardwareWallet.wallet.disconnect();
                setConnectedHardwareWallet(null);
              }}
              className="btn btn-secondary w-full"
            >
              Disconnect
            </button>
          </div>
        ) : (
          <div>
            <p className="text-sm text-slate-400 mb-4">
              Connect a Ledger or Trezor hardware wallet for enhanced security.
              Your private keys never leave the device.
            </p>
            <button
              onClick={() => setShowHardwareConnect(true)}
              disabled={!isHardwareWalletSupported()}
              className="btn btn-primary w-full"
            >
              {isHardwareWalletSupported() ? 'Connect Hardware Wallet' : 'Not Supported in This Browser'}
            </button>
            {!isHardwareWalletSupported() && (
              <p className="text-xs text-amber-400 mt-2">
                Use Chrome, Edge, or Brave on desktop for hardware wallet support.
              </p>
            )}
          </div>
        )}
      </div>

      {/* Security */}
      <div className="card mb-6">
        <h2 className="text-lg font-semibold mb-4">{t('settings.security.title')}</h2>
        <div className="space-y-4">
          <div className="flex items-center justify-between p-3 bg-slate-900 rounded-lg">
            <div>
              <div className="font-medium">{t('settings.security.autoLock')}</div>
              <div className="text-sm text-slate-500">
                {t('settings.security.autoLockDescription')}
              </div>
            </div>
            <select className="bg-slate-800 border border-slate-700 rounded px-3 py-2">
              <option value="5">{t('settings.security.minutes', { count: 5 })}</option>
              <option value="15">{t('settings.security.minutes', { count: 15 })}</option>
              <option value="30">{t('settings.security.minutes', { count: 30 })}</option>
              <option value="60">{t('settings.security.hour')}</option>
              <option value="0">{t('settings.security.never')}</option>
            </select>
          </div>
        </div>
      </div>

      {/* Language */}
      <div className="card mb-6">
        <h2 className="text-lg font-semibold mb-4">{t('settings.language.title')}</h2>
        <LanguageSelector />
      </div>

      {/* Danger Zone */}
      <div className="card border-red-900">
        <h2 className="text-lg font-semibold text-red-400 mb-4">Danger Zone</h2>

        {!showDeleteConfirm ? (
          <button
            onClick={() => setShowDeleteConfirm(true)}
            className="btn btn-danger"
          >
            Delete Wallet
          </button>
        ) : (
          <div className="space-y-4">
            <div className="p-3 bg-red-900/30 border border-red-700 rounded-lg text-red-300 text-sm">
              <strong>Warning:</strong> This will permanently delete your wallet
              from this device. Make sure you have your recovery phrase backed up.
            </div>

            <div>
              <label className="block text-sm text-slate-400 mb-2">
                Type "DELETE" to confirm
              </label>
              <input
                type="text"
                value={deleteConfirmText}
                onChange={(e) => setDeleteConfirmText(e.target.value)}
                className="input"
                placeholder="DELETE"
              />
            </div>

            <div className="flex gap-3">
              <button
                onClick={() => {
                  setShowDeleteConfirm(false);
                  setDeleteConfirmText('');
                }}
                className="btn btn-secondary flex-1"
              >
                Cancel
              </button>
              <button
                onClick={handleDeleteWallet}
                disabled={deleteConfirmText !== 'DELETE'}
                className="btn btn-danger flex-1"
              >
                Confirm Delete
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Version */}
      <div className="mt-6 text-center text-sm text-slate-500">
        Synor Web Wallet v0.1.0
      </div>

      {/* Hardware Wallet Connect Modal */}
      {showHardwareConnect && (
        <HardwareWalletConnect
          onAccountSelected={handleHardwareWalletConnected}
          onCancel={() => setShowHardwareConnect(false)}
        />
      )}
    </div>
  );
}
