'use client';
import React, { useEffect, useState } from 'react';

export type WalletOption = 'coinbase' | 'base' | 'metamask' | 'walletconnect';

interface WalletModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSelect: (wallet: WalletOption) => void;
  connecting: WalletOption | null;
}

const WALLET_CONSENT_KEY = 'vaultfire_wallet_consent_v1';

const WALLETS: { id: WalletOption; name: string; description: string; featured?: boolean; icon: React.ReactNode }[] = [
  {
    id: 'coinbase',
    name: 'Coinbase Wallet',
    description: 'Base-native smart wallet',
    featured: true,
    icon: (
      <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
        <rect width="32" height="32" rx="8" fill="#0052FF" />
        <path d="M16 6C10.48 6 6 10.48 6 16s4.48 10 10 10 10-4.48 10-10S21.52 6 16 6zm-2.5 13.5h5c.28 0 .5-.22.5-.5v-6c0-.28-.22-.5-.5-.5h-5c-.28 0-.5.22-.5.5v6c0 .28.22.5.5.5z" fill="white"/>
      </svg>
    ),
  },
  {
    id: 'base',
    name: 'Base Wallet',
    description: 'Built for the Base ecosystem',
    featured: true,
    icon: (
      <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
        <rect width="32" height="32" rx="8" fill="#0052FF" />
        <path d="M16 26c5.523 0 10-4.477 10-10S21.523 6 16 6 6 10.477 6 16s4.477 10 10 10z" fill="white"/>
        <path d="M15.96 22.16c3.42 0 6.2-2.78 6.2-6.2 0-3.42-2.78-6.2-6.2-6.2-3.18 0-5.8 2.4-6.14 5.48h8.18v1.44H9.82c.34 3.08 2.96 5.48 6.14 5.48z" fill="#0052FF"/>
      </svg>
    ),
  },
  {
    id: 'metamask',
    name: 'MetaMask',
    description: 'Popular browser wallet',
    icon: (
      <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
        <rect width="32" height="32" rx="8" fill="#F6851B" />
        <path d="M24.5 7L17.2 12.5l1.4-5L24.5 7z" fill="#E2761B" stroke="#E2761B" strokeWidth=".2"/>
        <path d="M7.5 7l7.2 5.6-1.3-5L7.5 7zm14.2 15.2l-1.9 3 4.1 1.1 1.2-4h-3.4zm-14.3.1l1.1 4 4.1-1.1-1.9-3h-3.3z" fill="#E4761B" stroke="#E4761B" strokeWidth=".2"/>
        <path d="M12.4 14.5l-1.2 1.8 4 .2-.1-4.4-2.7 2.4zm7.2 0l-2.8-2.5-.1 4.5 4-.2-1.1-1.8z" fill="#E4761B" stroke="#E4761B" strokeWidth=".2"/>
        <path d="M11.6 22.2l2.5-1.2-2.1-1.7-.4 2.9zm6.3-1.2l2.5 1.2-.4-2.9-2.1 1.7z" fill="#E4761B" stroke="#E4761B" strokeWidth=".2"/>
      </svg>
    ),
  },
  {
    id: 'walletconnect',
    name: 'WalletConnect',
    description: 'QR code for mobile wallets',
    icon: (
      <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
        <rect width="32" height="32" rx="8" fill="#3B99FC" />
        <path d="M10.8 13.2c2.9-2.8 7.5-2.8 10.4 0l.3.3c.1.1.1.4 0 .5l-1.1 1.1c-.1.1-.2.1-.3 0l-.5-.4c-2-2-5.2-2-7.2 0l-.5.5c-.1.1-.2.1-.3 0l-1.1-1.1c-.1-.1-.1-.4 0-.5l.3-.4zm12.8 2.4l1 1c.1.1.1.4 0 .5l-4.5 4.4c-.2.1-.4.1-.5 0l-3.2-3.1c0-.1-.1-.1-.1 0l-3.2 3.1c-.2.1-.4.1-.5 0L8.1 17c-.1-.1-.1-.4 0-.5l1-1c.2-.1.4-.1.5 0l3.2 3.1c0 .1.1.1.1 0l3.2-3.1c.2-.1.4-.1.5 0l3.2 3.1c0 .1.1.1.1 0l3.2-3.1c.2-.1.4-.1.5 0z" fill="white"/>
      </svg>
    ),
  },
];

export default function WalletModal({ isOpen, onClose, onSelect, connecting }: WalletModalProps) {
  const [agreed, setAgreed] = useState(false);

  // Auto-tick the box if the user has previously accepted in this browser
  useEffect(() => {
    if (!isOpen) return;
    try {
      const prev = window.localStorage.getItem(WALLET_CONSENT_KEY);
      if (prev) setAgreed(true);
    } catch {
      // localStorage may be unavailable; user just re-checks
    }
  }, [isOpen]);

  function persistConsent() {
    try {
      window.localStorage.setItem(
        WALLET_CONSENT_KEY,
        JSON.stringify({ acceptedAt: new Date().toISOString(), version: 1 })
      );
    } catch {
      // Best-effort persistence
    }
  }

  function handleSelect(wallet: WalletOption) {
    if (!agreed) return;
    persistConsent();
    onSelect(wallet);
  }

  if (!isOpen) return null;

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{
          position: 'fixed',
          inset: 0,
          backgroundColor: 'rgba(0,0,0,0.7)',
          backdropFilter: 'blur(8px)',
          zIndex: 9998,
          animation: 'fadeIn 150ms ease-out',
        }}
      />
      {/* Modal */}
      <div style={{
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        width: '100%',
        maxWidth: 420,
        backgroundColor: '#141417',
        border: '1px solid rgba(255,255,255,0.08)',
        borderRadius: 20,
        padding: 0,
        zIndex: 9999,
        boxShadow: '0 24px 80px rgba(0,0,0,0.6), 0 0 60px rgba(255,107,53,0.08)',
        animation: 'modalSlideIn 200ms ease-out',
        overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '20px 24px 16px',
          borderBottom: '1px solid rgba(255,255,255,0.06)',
        }}>
          <div>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: '#F4F4F5' }}>
              Connect Wallet
            </h2>
            <p style={{ margin: '4px 0 0', fontSize: 13, color: '#71717a' }}>
              Choose your preferred wallet
            </p>
          </div>
          <button
            onClick={onClose}
            style={{
              width: 32,
              height: 32,
              borderRadius: 8,
              border: 'none',
              backgroundColor: 'rgba(255,255,255,0.06)',
              color: '#71717a',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: 18,
              transition: 'all 150ms',
            }}
          >
            ✕
          </button>
        </div>

        {/* Wallet options */}
        <div style={{ padding: '12px 16px 20px' }}>
          {/* Featured wallets */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
            {WALLETS.filter(w => w.featured).map(wallet => (
              <button
                key={wallet.id}
                onClick={() => handleSelect(wallet.id)}
                disabled={!!connecting || !agreed}
                title={!agreed ? 'Agree to the terms below to connect' : undefined}
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 10,
                  padding: '20px 16px',
                  borderRadius: 14,
                  border: '1px solid rgba(255,255,255,0.08)',
                  backgroundColor: 'rgba(255,255,255,0.03)',
                  color: '#F4F4F5',
                  cursor: !agreed ? 'not-allowed' : connecting ? 'wait' : 'pointer',
                  transition: 'all 150ms',
                  opacity: !agreed ? 0.45 : connecting && connecting !== wallet.id ? 0.4 : 1,
                }}
              >
                {wallet.icon}
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>
                    {connecting === wallet.id ? 'Connecting...' : wallet.name}
                  </div>
                  <div style={{ fontSize: 11, color: '#71717a', marginTop: 2 }}>{wallet.description}</div>
                </div>
                {wallet.id === 'coinbase' && (
                  <span style={{
                    fontSize: 10,
                    fontWeight: 600,
                    color: '#0052FF',
                    backgroundColor: 'rgba(0,82,255,0.12)',
                    padding: '2px 8px',
                    borderRadius: 6,
                    letterSpacing: '0.02em',
                  }}>
                    RECOMMENDED
                  </span>
                )}
              </button>
            ))}
          </div>

          {/* Other wallets */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {WALLETS.filter(w => !w.featured).map(wallet => (
              <button
                key={wallet.id}
                onClick={() => handleSelect(wallet.id)}
                disabled={!!connecting || !agreed}
                title={!agreed ? 'Agree to the terms below to connect' : undefined}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 14,
                  padding: '14px 16px',
                  borderRadius: 12,
                  border: '1px solid rgba(255,255,255,0.06)',
                  backgroundColor: 'rgba(255,255,255,0.02)',
                  color: '#F4F4F5',
                  cursor: !agreed ? 'not-allowed' : connecting ? 'wait' : 'pointer',
                  transition: 'all 150ms',
                  opacity: !agreed ? 0.45 : connecting && connecting !== wallet.id ? 0.4 : 1,
                  width: '100%',
                  textAlign: 'left',
                }}
              >
                {wallet.icon}
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>
                    {connecting === wallet.id ? 'Connecting...' : wallet.name}
                  </div>
                  <div style={{ fontSize: 12, color: '#71717a' }}>{wallet.description}</div>
                </div>
                <svg style={{ marginLeft: 'auto' }} width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#52525b" strokeWidth="2">
                  <path d="M9 18l6-6-6-6" />
                </svg>
              </button>
            ))}
          </div>
        </div>

        {/* Legal acceptance gate */}
        <div style={{
          padding: '14px 20px 16px',
          borderTop: '1px solid rgba(255,255,255,0.06)',
          backgroundColor: 'rgba(255,140,90,0.04)',
        }}>
          <label style={{
            display: 'flex',
            alignItems: 'flex-start',
            gap: 10,
            cursor: 'pointer',
            userSelect: 'none',
          }}>
            <input
              type="checkbox"
              checked={agreed}
              onChange={(e) => setAgreed(e.target.checked)}
              aria-label="Agree to terms, privacy policy, and disclaimer"
              style={{
                marginTop: 2,
                width: 16,
                height: 16,
                accentColor: '#FF6B35',
                cursor: 'pointer',
                flexShrink: 0,
              }}
            />
            <span style={{ fontSize: 12, color: '#a1a1aa', lineHeight: 1.5 }}>
              I have read and agree to the{' '}
              <a
                href="/terms"
                target="_blank"
                rel="noopener noreferrer"
                onClick={(e) => e.stopPropagation()}
                style={{ color: '#FF8C5A', textDecoration: 'underline' }}
              >
                Terms of Service
              </a>
              ,{' '}
              <a
                href="/privacy"
                target="_blank"
                rel="noopener noreferrer"
                onClick={(e) => e.stopPropagation()}
                style={{ color: '#FF8C5A', textDecoration: 'underline' }}
              >
                Privacy Policy
              </a>
              , and{' '}
              <a
                href="/disclaimer"
                target="_blank"
                rel="noopener noreferrer"
                onClick={(e) => e.stopPropagation()}
                style={{ color: '#FF8C5A', textDecoration: 'underline' }}
              >
                Disclaimer
              </a>
              . I understand bonds are performance collateral, not investments, and the protocol is in alpha.
            </span>
          </label>
        </div>
      </div>

      <style>{`
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        @keyframes modalSlideIn {
          from { opacity: 0; transform: translate(-50%, -48%); }
          to { opacity: 1; transform: translate(-50%, -50%); }
        }
      `}</style>
    </>
  );
}
