"use client";

import React, { useState, useEffect } from "react";
import { 
  useIsInitialized, 
  useIsSignedIn, 
  useEvmAddress, 
  useSignInWithEmail, 
  useVerifyEmailOTP, 
  useSignOut,
  useCurrentUser,
  type User
} from "@coinbase/cdp-hooks";
import { getEvmAddress, getCurrentUser, getIsInitialized, getHookActions, validateHookReturns } from '../lib/hook-utils';

export interface CustomWalletAuthProps {
  className?: string;
  showDebugInfo?: boolean;
  onSignedIn?: (user: User, address: string) => void;
  onSignedOut?: () => void;
  theme?: 'light' | 'dark';
}

/**
 * Custom wallet authentication component with full control over the UI/UX.
 * Provides email + OTP authentication flow with state management.
 * 
 * @example
 * ```tsx
 * import { CustomWalletAuth } from 'cdp-wallet-onramp-kit';
 * 
 * function WalletSection() {
 *   return (
 *     <CustomWalletAuth 
 *       theme="dark"
 *       onSignedIn={(user, address) => {
 *         console.log('User signed in:', user, address);
 *       }}
 *     />
 *   );
 * }
 * ```
 */
export function CustomWalletAuth({ 
  className = "",
  showDebugInfo = false,
  onSignedIn,
  onSignedOut,
  theme = 'light'
}: CustomWalletAuthProps) {
  // Raw hook results
  const isInitializedResult = useIsInitialized();
  const isSignedInResult = useIsSignedIn();
  const evmAddressResult = useEvmAddress();
  const signInWithEmailResult = useSignInWithEmail();
  const verifyEmailOTPResult = useVerifyEmailOTP();
  const signOutResult = useSignOut();
  const currentUserResult = useCurrentUser();

  // Normalized values using defensive type handling
  const isInitialized = getIsInitialized(isInitializedResult);
  const isSignedIn = typeof isSignedInResult === 'boolean' ? isSignedInResult : !!isSignedInResult?.isSignedIn;
  const evmAddress = getEvmAddress(evmAddressResult);
  const { signInWithEmail } = getHookActions(signInWithEmailResult);
  const { verifyEmailOTP } = getHookActions(verifyEmailOTPResult);
  const { signOut } = getHookActions(signOutResult);
  const currentUser = getCurrentUser(currentUserResult);
  
  const [email, setEmail] = useState("");
  const [otp, setOtp] = useState("");
  const [flowId, setFlowId] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Theme styles
  const isDark = theme === 'dark';
  const bgClass = isDark ? 'bg-gray-800' : 'bg-white';
  const textClass = isDark ? 'text-white' : 'text-gray-900';
  const mutedTextClass = isDark ? 'text-gray-300' : 'text-gray-600';
  const inputClass = isDark 
    ? 'bg-gray-700 text-white placeholder-gray-400 border-gray-600' 
    : 'bg-white text-gray-900 placeholder-gray-500 border-gray-300';
  const buttonClass = isDark
    ? 'bg-blue-600 hover:bg-blue-700 text-white'
    : 'bg-blue-500 hover:bg-blue-600 text-white';

  // Development validation
  useEffect(() => {
    if (process.env.NODE_ENV === 'development') {
      validateHookReturns({
        evmAddress: evmAddressResult,
        currentUser: currentUserResult,
        isInitialized: isInitializedResult
      });
    }
  }, [evmAddressResult, currentUserResult, isInitializedResult]);

  // Effect to call onSignedIn when user signs in
  useEffect(() => {
    if (isSignedIn && currentUser && evmAddress && onSignedIn) {
      onSignedIn(currentUser, evmAddress);
    }
  }, [isSignedIn, currentUser, evmAddress, onSignedIn]);

  // Debug logging
  useEffect(() => {
    if (showDebugInfo) {
      console.log("CustomWalletAuth State:", {
        isInitialized,
        isSignedIn,
        evmAddress: evmAddress || null,
        flowId,
        hasProjectId: !!process.env.NEXT_PUBLIC_CDP_PROJECT_ID,
      });
    }
  }, [isInitialized, isSignedIn, evmAddress, flowId, showDebugInfo]);

  if (!isInitialized) {
    return (
      <div className={`text-center py-8 ${className}`}>
        <div className={mutedTextClass}>Loading wallet...</div>
        {showDebugInfo && (
          <div className="text-xs text-gray-500 mt-2">
            Project ID: {process.env.NEXT_PUBLIC_CDP_PROJECT_ID ? 'Set' : 'Missing'}
          </div>
        )}
      </div>
    );
  }

  const handleEmailSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);
    
    try {
      const { flowId } = await signInWithEmail({ email });
      setFlowId(flowId);
    } catch (error) {
      setError(error instanceof Error ? error.message : "Sign in failed");
    } finally {
      setIsLoading(false);
    }
  };

  const handleOtpSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!flowId) return;
    
    setIsLoading(true);
    setError(null);
    
    try {
      await verifyEmailOTP({ flowId, otp });
      setFlowId(null);
      setOtp("");
    } catch (error) {
      setError(error instanceof Error ? error.message : "OTP verification failed");
    } finally {
      setIsLoading(false);
    }
  };

  const handleSignOut = async () => {
    try {
      await signOut();
      if (onSignedOut) {
        onSignedOut();
      }
    } catch (error) {
      setError(error instanceof Error ? error.message : "Sign out failed");
    }
  };

  // Show sign in form when not signed in and no flow in progress
  if (!isSignedIn && !flowId) {
    return (
      <div className={`space-y-6 ${className}`}>
        <div className="flex items-center justify-between">
          <h2 className={`text-lg font-medium ${textClass}`}>Embedded Wallet</h2>
        </div>
        
        {error && (
          <div className={`${isDark ? 'bg-red-900/20 border-red-500/30' : 'bg-red-50 border-red-200'} border p-3 rounded-lg`}>
            <p className={`${isDark ? 'text-red-300' : 'text-red-700'} text-sm`}>{error}</p>
          </div>
        )}
        
        <form onSubmit={handleEmailSubmit} className="space-y-4">
          <div>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="Enter your email"
              className={`${inputClass} w-full px-4 py-2 rounded-lg border focus:outline-none focus:ring-2 focus:ring-blue-500`}
              required
            />
          </div>
          <button
            type="submit"
            disabled={isLoading}
            className={`${buttonClass} w-full py-2 px-4 rounded-lg text-sm font-medium disabled:opacity-50 transition-colors`}
          >
            {isLoading ? "Sending..." : "Sign in"}
          </button>
        </form>
      </div>
    );
  }

  // Show OTP form when flow is in progress
  if (!isSignedIn && flowId) {
    return (
      <div className={`space-y-6 ${className}`}>
        <div className="flex items-center justify-between">
          <h2 className={`text-lg font-medium ${textClass}`}>Verify Email</h2>
        </div>
        
        {error && (
          <div className={`${isDark ? 'bg-red-900/20 border-red-500/30' : 'bg-red-50 border-red-200'} border p-3 rounded-lg`}>
            <p className={`${isDark ? 'text-red-300' : 'text-red-700'} text-sm`}>{error}</p>
          </div>
        )}
        
        <form onSubmit={handleOtpSubmit} className="space-y-4">
          <div className={`text-sm ${mutedTextClass} mb-2`}>
            Enter the 6-digit code sent to {email}
          </div>
          <div>
            <input
              type="text"
              value={otp}
              onChange={(e) => setOtp(e.target.value)}
              placeholder="Enter 6-digit code"
              maxLength={6}
              className={`${inputClass} w-full px-4 py-2 rounded-lg border focus:outline-none focus:ring-2 focus:ring-blue-500 text-center text-lg tracking-widest`}
              required
            />
          </div>
          <button
            type="submit"
            disabled={isLoading}
            className={`${buttonClass} w-full py-2 px-4 rounded-lg text-sm font-medium disabled:opacity-50 transition-colors`}
          >
            {isLoading ? "Verifying..." : "Verify Code"}
          </button>
          <button
            type="button"
            onClick={() => {
              setFlowId(null);
              setOtp("");
              setError(null);
            }}
            className={`${mutedTextClass} w-full text-sm hover:underline`}
          >
            Back to email
          </button>
        </form>
      </div>
    );
  }

  // Show signed in state
  return (
    <div className={`space-y-6 ${className}`}>
      <div className="flex items-center justify-between">
        <h2 className={`text-lg font-medium ${textClass}`}>Wallet Connected</h2>
      </div>
      
      {error && (
        <div className={`${isDark ? 'bg-red-900/20 border-red-500/30' : 'bg-red-50 border-red-200'} border p-3 rounded-lg`}>
          <p className={`${isDark ? 'text-red-300' : 'text-red-700'} text-sm`}>{error}</p>
        </div>
      )}
      
      <div className="space-y-4">
        <div className="flex items-center gap-2">
          <div className="w-2 h-2 bg-green-400 rounded-full"></div>
          <span className={`${mutedTextClass} text-sm`}>Wallet Connected</span>
        </div>
        
        {evmAddress && (
          <div className={`${bgClass} p-3 rounded-lg border ${isDark ? 'border-gray-600' : 'border-gray-200'}`}>
            <div className={`text-xs ${mutedTextClass} mb-1`}>Address:</div>
            <code className={`text-sm font-mono ${textClass} break-all`}>
              {evmAddress}
            </code>
          </div>
        )}
        
        <button
          onClick={handleSignOut}
          className={`${mutedTextClass} hover:${textClass} w-full py-2 px-4 rounded-lg text-sm border transition-colors ${isDark ? 'border-gray-600 hover:border-gray-500' : 'border-gray-300 hover:border-gray-400'}`}
        >
          Sign out
        </button>
      </div>
    </div>
  );
}