import { SignIn } from '@clerk/nextjs';

// Define explicit types for error messages
type ErrorInfo = {
  title: string;
  message: string;
};

// Define all possible error codes explicitly
type ErrorCode =
  | 'auth_already_associated'
  | 'auth_canceled'
  | 'auth_failed'
  | 'auth_missing_parameter'
  | 'auth_state_forbidden'
  | 'auth_state_missing'
  | 'auth_token_error'
  | 'auth_token_revoked'
  | 'auth_unknown_error'
  | 'auth_unreachable_provider'
  | 'client_not_found'
  | 'client_user_not_found'
  | 'client_verification_failed'
  | 'identifier_required'
  | 'invalid_client_request'
  | 'invalid_strategy'
  | 'support_needed'
  | 'not_allowed_to_disconnect'
  | 'not_found'
  | 'not_implemented'
  | 'phone_pre_verification_failed_code'
  | 'phone_verification_failed_code'
  | 'phone_verification_too_many_attempts_code'
  | 'rate_limit_block'
  | 'redirect_url_required'
  | 'session_not_found'
  | 'system_error'
  | 'turnstile_initialization_failed'
  | 'wrong_backend';

// Error code to user-friendly message mapping
const ERROR_MESSAGES: Record<ErrorCode, ErrorInfo> = {
  // Authentication errors
  auth_already_associated: {
    title: 'Account Already Associated',
    message: 'This social account is already associated with another user.',
  },
  auth_canceled: {
    title: 'Authentication Canceled',
    message: 'Authentication was canceled. Please try again.',
  },
  auth_failed: {
    title: 'Authentication Failed',
    message: 'Authentication failed. Please try again.',
  },
  auth_missing_parameter: {
    title: 'Missing Parameter',
    message: 'Required authentication parameter is missing. Please try again.',
  },
  auth_state_forbidden: {
    title: 'Invalid State',
    message: 'Authentication state is invalid. Please try again.',
  },
  auth_state_missing: {
    title: 'Missing State',
    message: 'Authentication state is missing. Please try again.',
  },
  auth_token_error: {
    title: 'Token Error',
    message: 'Authentication token error. Please sign in again.',
  },
  auth_token_revoked: {
    title: 'Token Revoked',
    message: 'Authentication token has been revoked. Please sign in again.',
  },
  auth_unknown_error: {
    title: 'Unknown Error',
    message:
      'An unknown error occurred during authentication. Please try again.',
  },
  auth_unreachable_provider: {
    title: 'Provider Unreachable',
    message: 'Unable to reach authentication provider. Please try again later.',
  },
  client_not_found: {
    title: 'Client Not Found',
    message:
      'Client session not found. Please try clearing cookies and signing in again.',
  },
  client_user_not_found: {
    title: 'User Not Found',
    message:
      'Client user not found. Please try clearing cookies and signing in again.',
  },
  client_verification_failed: {
    title: 'Verification Failed',
    message: 'Please contact support.',
  },
  identifier_required: {
    title: 'Identifier Required',
    message: 'Identifier is required.',
  },
  invalid_client_request: {
    title: 'Invalid Request',
    message: 'Please try again.',
  },
  invalid_strategy: {
    title: 'Invalid Strategy',
    message: 'Invalid authentication strategy provided.',
  },
  support_needed: {
    title: 'Support Needed',
    message: 'Please contact support.',
  },
  not_allowed_to_disconnect: {
    title: 'Cannot Disconnect',
    message: 'Cannot disconnect this account. Please set a password first.',
  },
  not_found: {
    title: 'Not Found',
    message: 'Not found.',
  },
  not_implemented: {
    title: 'Not Implemented',
    message: 'This endpoint is not implemented.',
  },
  phone_pre_verification_failed_code: {
    title: 'Phone Verification Failed',
    message: 'Please contact support.',
  },
  phone_verification_failed_code: {
    title: 'Phone Verification Failed',
    message: 'Phone verification failed.',
  },
  phone_verification_too_many_attempts_code: {
    title: 'Too Many Attempts',
    message: 'Phone verification failed. Too many attempts.',
  },
  rate_limit_block: {
    title: 'Too Many Requests',
    message: 'Too many requests. Please try again later.',
  },
  redirect_url_required: {
    title: 'Redirect URL Required',
    message: 'Redirect URL is required.',
  },
  session_not_found: {
    title: 'Session Not Found',
    message:
      'Session not found. Please try clearing cookies and signing in again.',
  },
  system_error: {
    title: 'System Error',
    message: 'Our team has been notified. Please try again later.',
  },
  turnstile_initialization_failed: {
    title: 'Initialization Error',
    message: 'Please contact support.',
  },
  wrong_backend: {
    title: 'Invalid Provider',
    message: 'Invalid authentication provider. Please try again.',
  },
} as const;

function isErrorCode(key: string): key is ErrorCode {
  return key in ERROR_MESSAGES;
}

interface AuthErrorPageProps {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}

export default async function AuthErrorPage({
  searchParams,
}: AuthErrorPageProps): Promise<React.JSX.Element> {
  const resolvedSearchParams = await searchParams;
  const errorCodeParam = resolvedSearchParams.error_code;
  const traceIdParam = resolvedSearchParams.trace_id;

  // Use the type guard to safely check if the error code is valid
  const errorCode: ErrorCode =
    typeof errorCodeParam === 'string' && isErrorCode(errorCodeParam)
      ? errorCodeParam
      : 'system_error';
  const errorInfo: ErrorInfo = ERROR_MESSAGES[errorCode];

  // Safely extract trace ID as a string (take first value if array)
  const traceId: string | null =
    typeof traceIdParam === 'string'
      ? traceIdParam
      : Array.isArray(traceIdParam) && traceIdParam.length > 0
        ? traceIdParam[0]
        : null;

  return (
    <div className='flex min-h-screen w-full flex-col items-center justify-center px-4'>
      <div className='w-full max-w-md space-y-6'>
        <div className='text-center'>
          <h1 className='mb-4 text-2xl font-bold text-foreground-primary'>
            {errorInfo.title}
          </h1>

          <p className='mb-4 text-foreground-secondary'>{errorInfo.message}</p>

          {traceId && (
            <p className='mb-4 text-xs text-foreground-tertiary'>
              Trace ID: {traceId}
            </p>
          )}

          <p className='text-sm text-foreground-tertiary'>
            Please try again by signing in below:
          </p>
        </div>

        <div className='flex justify-center'>
          <SignIn
            appearance={{
              elements: {
                formButtonPrimary:
                  'bg-accent-pink-on-primary text-white hover:bg-accent-pink-on-primary/90',
                card: 'shadow-lg',
              },
            }}
          />
        </div>
      </div>
    </div>
  );
}
